php - Symfony2 How to have access to a set of data in all controllers? -


i have searched can't find similar issues or maybe phrasing wrong. want achieve access object in controllers in bundle. example:

<?php  namespace example\corebundle\controller;  use symfony\bundle\frameworkbundle\controller\controller;  class foldercontroller extends controller {      function indexaction()     {           $title = $this->folder->gettitle();          $description = $this->folder->getdescription();      }  } 

usually outside of symfony have extended controller class myself basecontroller extends controller , set in construct method know symfony doesn't use construct method bit stuck go.

i this:

class basecontroller extends controller {       function __construct()      {            parent::__construct();           //load folder model id           $this->folder = $folder;       }  } 

i extend basecontroller foldercontroller , go there have tried symfony , not work. have looked services not think need make work. if more details required please let me know, thanks.

if understand question correctly, services indeed you're looking for.

first, define service in services.yml:

services:     vendor.folder_manager:         class: vendor\folderbundle\entity\manager\foldermanager         arguments:             em: "@doctrine.orm.entity_manager"             class: vendor\folderbundle\entity\folder 

then create foldermanager class:

<?php namespace vendor\folderbundle\entity\manager;  use doctrine\orm\entitymanager; use doctrine\orm\entityrepository;  class foldermanager {     protected $em;      protected $repo;      protected $class;      public function __construct(entitymanager $em, $class) {         $this->em = $em;         $this->class = $class;         $this->repo = $em->getrepository($class);     }      public function findbyid($id) {         return $this->repo->findbyid($id);     }      public function getrepository() {         return $this->repo;     } } 

finally, in controller:

$this->container->get('vendor.folder_manager')->findbyid($folderid); 

or:

$this->container->get('vendor.folder_manager')->getrepository()->findbyid($folderid); 

symfony2 automatically inject entity manager class manager, have provide in controller folder's id.

edit: make prettier, make shortcut function in controller:

protected function getfoldermanager() {     return $this->container->get('vendor.folder_manager'); } 

then can do:

$this->getfoldermanager()->findbyid($folderid); 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -