php - Accessing Silex Application class from other classes; how to inject? -


i'm working on first silex (2.0) project. have pheasant models defined, can access within controller:

// used both static $p = \model\post::onebyid(3);  // .. , instance $p = new \model\post; $p->title = 'foobar'; $p->save(); 

now, in cases i'd access application class within model. example, check if we're running in debug mode (or not). right now:

public function beforesave() {     global $app;     if($app['debug']) {         // ...     } } 

but doesn't feel silex. figured need kind of thing that'll automatically inject $app class models:

class pheasantmodelreflector {     protected $app;      public function __construct(\silex\application $app) {         $this->app = $app;     }      public function __get($classname) {         $r = (new reflectionclass(sprintf('model\%s', $classname)))->newinstance();         $r->__invoke($this->app);         return $r;     } }  $app['model'] = function ($app) {     return new pheasantmodelreflector($app); }; 

this works level, returns new instance of post model when called $app['model']->post.

is there way fix this?

without having worked pheasant, may try create service factory injects $app (or $debug var) entity class (one problem here entity must extend \pheasant\domainobject , can't override constructor it's marked final):

<?php  // in example below inject whole $app, if need // debug var, inject that, injecting whole $app may // tempt use service locator  // creating new instance $app['model_post_factory'] = $app->factory(function ($app) {   $post = new \model\post();   $post->setapp($app);     return $post; });  $post = $app['model_post_factory'];  // getting instance id, here gets little tricky $app['model_post_static_factory'] = function($app, $id) {   $post = \model\post::onebyid($id);   $post->setapp($app);    return $post; }  $postbyid = $app->raw('model_post_static_factory'); $post = $postbyid($app, $id);  // $id comes somewhere else  // depending on php version may try directly: // $post = $app->raw('model_post_static_factory')($app, $id); 

the problem static method passing id parameter. can import factory scope $id outside scope using use keyword, imho magic (though don't quite alternative either). there may more elegant way, can't think of right now.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -