You really need to use service containers, which are basically symfony's way of loading classes.
That's why:
- Namely, the service is never built until it is needed.
- Best practice for code reuse.
- Separating every functionality of your application.
- Since each service performs only one task, you can easily access each service and use its functionality wherever you need.
- Each service can also be more easily tested and configured since it is separated from other functions of your application.
- This idea is called service-oriented architecture and is not unique to Symfony or even to PHP.
http://symfony.com/doc/current/book/service_container.html
A Service Container (or dependency injection container) is simply a PHP object that manages the instantiation of services (ie objects).
That way, basically symfony will process the class instances for you in your controller. All you have to do is the following:
Add a folder under your path called Libraries โ src / AppBundle / Libraries
Add a class to this folder with the namespace at the top. My example:
<?php namespace AppBundle\Libraries; class MyRecommendations{ public function __construct(){ } public function init(){ die("init"); } }
Then add a file called services.yml to your application. application /Config/services.yml
Put the following code in it, don't use tabs in yml file
services: myrecommendations: class: AppBundle\Libraries\MyRecommendations #arguments: [specialparamhere] #constructor parameters here
Then add the resources of the third line: services.yml to the config.yml file.
imports: - { resource: parameters.yml } - { resource: security.yml } - { resource: services.yml }
At the top of your controller, when using, simply add a usage statement
use AppBundle\Libraries\MyRecommendations;
Now call your code
$test = $this->get('myrecommendations'); $test->init();
echo out
init
Jason
source share