php - Slim - Swift Mailer on the route is work but if after moved on controller get errors -
i add libraries slimcontroller , swift mailer in slim project, when in route goes well:
route::get('/send', function() use ($app, $mailer) { $message = swift_message::newinstance('activation code') ->setfrom(array('xxx@gmail.com' => 'xxx')) ->setto(array('xxxs@gmail.com' => 'xxxs')) ->setbody('test'); // send message $results = $mailer->send($message); // print results, 1 = message sent! print($results); });
but after run on controller there error
class mycontroller extends \slimcontroller\slimcontroller { public function getregisters() { $data = (empty(\session::flash())) ? array( 'token' => \token::gettoken() ) : array_merge(\session::flash(), array( 'token' => \token::gettoken() )); return $this->render('auth/register.html', $data); } public function postregisters() { $message = swift_message::newinstance('activation code')->setfrom(array( 'xxx@gmail.com' => 'xxx' ))->setto(array( 'xxxs@gmail.com' => 'xxxs' ))->setbody('test'); // send message $results = $this->app->mailer->send($message); } }
fatal error: call member function send() on non-object in.
reference fortrabbit/slimcontroller
i'm guessing here (since don' have full controller code) controller's $this->app
empty. slim won't inject $app
object in controllers.
there several ways inject dependencies slim. i'm not entirely sure what's best practice here. i'd start looking here.
also, can nasty hack in controllers __construct
. although don't recommend it, like:
class controller { protected $app; public function __construct() { $this->app = \slim\slim::getinstance(); } }
if sure controller have $app
property, problem how inject $mailer
instance. see routes, you're passing both $app
, $mailer
closure.
you can inject mailer object app singleton. code should like:
$app->mailer = function() { $mailer = new whatevermaileryouareusing(); // ...config stuff... return $mailer; };
Comments
Post a Comment