I'm relatively new to Symfony (version 4) and have put together a REST API using the framework.
I have several controllers corresponding to endpoints many of which use common services. One service is common to every controller.
Currently I am injecting these services manually into each controller.
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use App\Services\Utilities;
use App\Services\Database;
use App\Services\Session;
use App\Services\Rest;
class Fetch extends Controller {
protected $API;
protected $DB;
protected $u;
public function init() {
$this->API = new Rest();
$this->DB = new Database();
$this->u = new Utilities();
$this->API->init();
$this->DB->init($this->DB->default_credentials);
// ....
Its kinda repetitive and not very efficient since each class needs to be instantiated every time an endpoint is requested.
There is a need for a global base controller.
Having browsed the Symfony docs & stackoverflow posts, it looks like I can create a base controller and have all my other controllers extend
it like so:
class Fetch extends BaseController {
//.....
And all the methods in BaseController
will be available in Fetch
. Moreover, I can run hooks in BaseController
that will run globally (as long as all my controllers extend BaseController
.
I have also come upon this symfony docs article describing implementation of "Before and After Filters" that hook into all requests.
Which method (BaseController / Before and After Filters) would be best appropriate for what is effectively some code I want to run globally every time a request is made & why?