Dependency Injection / Service Location

DI explained

The following example is a bit long, but it attempts to explain why Phalcon uses service location and dependency injection. First, let’s assume we are developing a component called SomeComponent. This performs some task. Our component has a dependency, that is a connection to a database.

In this first example, the connection is created inside the component. Although this is a perfectly valid implementation, it is impartical, due to the fact that we cannot change the connection parameters or the type of the database system because the component only works as created.

  1. <?php
  2. class SomeComponent
  3. {
  4. /**
  5. * The instantiation of the connection is hardcoded inside
  6. * the component, therefore it's difficult replace it externally
  7. * or change its behavior
  8. */
  9. public function someDbTask()
  10. {
  11. $connection = new Connection(
  12. [
  13. 'host' => 'localhost',
  14. 'username' => 'root',
  15. 'password' => 'secret',
  16. 'dbname' => 'invo',
  17. ]
  18. );
  19. // ...
  20. }
  21. }
  22. $some = new SomeComponent();
  23. $some->someDbTask();

To solve this shortcoming, we have created a setter that injects the dependency externally before using it. This is also a valid implementation but has its shortcomings:

  1. <?php
  2. class SomeComponent
  3. {
  4. private $connection;
  5. /**
  6. * Sets the connection externally
  7. *
  8. * @param Connection $connection
  9. */
  10. public function setConnection(Connection $connection)
  11. {
  12. $this->connection = $connection;
  13. }
  14. public function someDbTask()
  15. {
  16. $connection = $this->connection;
  17. // ...
  18. }
  19. }
  20. $some = new SomeComponent();
  21. // Create the connection
  22. $connection = new Connection(
  23. [
  24. 'host' => 'localhost',
  25. 'username' => 'root',
  26. 'password' => 'secret',
  27. 'dbname' => 'invo',
  28. ]
  29. );
  30. // Inject the connection in the component
  31. $some->setConnection($connection);
  32. $some->someDbTask();

Now consider that we use this component in different parts of the application and then we will need to create the connection several times before passing it to the component. Using a global registry pattern, we can store the connection object there and reuse it whenever we need it.

  1. <?php
  2. class Registry
  3. {
  4. /**
  5. * Returns the connection
  6. */
  7. public static function getConnection()
  8. {
  9. return new Connection(
  10. [
  11. 'host' => 'localhost',
  12. 'username' => 'root',
  13. 'password' => 'secret',
  14. 'dbname' => 'invo',
  15. ]
  16. );
  17. }
  18. }
  19. class SomeComponent
  20. {
  21. protected $connection;
  22. /**
  23. * Sets the connection externally
  24. *
  25. * @param Connection $connection
  26. */
  27. public function setConnection(Connection $connection)
  28. {
  29. $this->connection = $connection;
  30. }
  31. public function someDbTask()
  32. {
  33. $connection = $this->connection;
  34. // ...
  35. }
  36. }
  37. $some = new SomeComponent();
  38. // Pass the connection defined in the registry
  39. $some->setConnection(Registry::getConnection());
  40. $some->someDbTask();

Now, let’s imagine that we must implement two methods in the component, the first always needs to create a new connection and the second always needs to use a shared connection:

  1. <?php
  2. class Registry
  3. {
  4. protected static $connection;
  5. /**
  6. * Creates a connection
  7. *
  8. * @return Connection
  9. */
  10. protected static function createConnection(): Connection
  11. {
  12. return new Connection(
  13. [
  14. 'host' => 'localhost',
  15. 'username' => 'root',
  16. 'password' => 'secret',
  17. 'dbname' => 'invo',
  18. ]
  19. );
  20. }
  21. /**
  22. * Creates a connection only once and returns it
  23. *
  24. * @return Connection
  25. */
  26. public static function getSharedConnection(): Connection
  27. {
  28. if (self::$connection === null) {
  29. self::$connection = self::createConnection();
  30. }
  31. return self::$connection;
  32. }
  33. /**
  34. * Always returns a new connection
  35. *
  36. * @return Connection
  37. */
  38. public static function getNewConnection(): Connection
  39. {
  40. return self::createConnection();
  41. }
  42. }
  43. class SomeComponent
  44. {
  45. protected $connection;
  46. /**
  47. * Sets the connection externally
  48. *
  49. * @param Connection $connection
  50. */
  51. public function setConnection(Connection $connection)
  52. {
  53. $this->connection = $connection;
  54. }
  55. /**
  56. * This method always needs the shared connection
  57. */
  58. public function someDbTask()
  59. {
  60. $connection = $this->connection;
  61. // ...
  62. }
  63. /**
  64. * This method always needs a new connection
  65. *
  66. * @param Connection $connection
  67. */
  68. public function someOtherDbTask(Connection $connection)
  69. {
  70. }
  71. }
  72. $some = new SomeComponent();
  73. // This injects the shared connection
  74. $some->setConnection(
  75. Registry::getSharedConnection()
  76. );
  77. $some->someDbTask();
  78. // Here, we always pass a new connection as parameter
  79. $some->someOtherDbTask(
  80. Registry::getNewConnection()
  81. );

So far we have seen how dependency injection solved our problems. Passing dependencies as arguments instead of creating them internally in the code makes our application more maintainable and decoupled. However, in the long-term, this form of dependency injection has some disadvantages.

For instance, if the component has many dependencies, we will need to create multiple setter arguments to pass the dependencies or create a constructor that pass them with many arguments, additionally creating dependencies before using the component, every time, makes our code not as maintainable as we would like:

  1. <?php
  2. // Create the dependencies or retrieve them from the registry
  3. $connection = new Connection();
  4. $session = new Session();
  5. $fileSystem = new FileSystem();
  6. $filter = new Filter();
  7. $selector = new Selector();
  8. // Pass them as constructor parameters
  9. $some = new SomeComponent($connection, $session, $fileSystem, $filter, $selector);
  10. // ... Or using setters
  11. $some->setConnection($connection);
  12. $some->setSession($session);
  13. $some->setFileSystem($fileSystem);
  14. $some->setFilter($filter);
  15. $some->setSelector($selector);

Think if we had to create this object in many parts of our application. In the future, if we do not require any of the dependencies, we need to go through the entire code base to remove the parameter in any constructor or setter where we injected the code. To solve this, we return again to a global registry to create the component. However, it adds a new layer of abstraction before creating the object:

  1. <?php
  2. class SomeComponent
  3. {
  4. // ...
  5. /**
  6. * Define a factory method to create SomeComponent instances injecting its dependencies
  7. */
  8. public static function factory()
  9. {
  10. $connection = new Connection();
  11. $session = new Session();
  12. $fileSystem = new FileSystem();
  13. $filter = new Filter();
  14. $selector = new Selector();
  15. return new self($connection, $session, $fileSystem, $filter, $selector);
  16. }
  17. }

Now we find ourselves back where we started, we are again building the dependencies inside of the component! We must find a solution that keeps us from repeatedly falling into bad practices.

A practical and elegant way to solve these problems is using a container for dependencies. The containers act as the global registry that we saw earlier. Using the container for dependencies as a bridge to obtain the dependencies allows us to reduce the complexity of our component:

  1. <?php
  2. use Phalcon\Di;
  3. use Phalcon\DiInterface;
  4. class SomeComponent
  5. {
  6. protected $di;
  7. public function __construct(DiInterface $di)
  8. {
  9. $this->di = $di;
  10. }
  11. public function someDbTask()
  12. {
  13. // Get the connection service
  14. // Always returns a new connection
  15. $connection = $this->di->get('db');
  16. }
  17. public function someOtherDbTask()
  18. {
  19. // Get a shared connection service,
  20. // this will return the same connection every time
  21. $connection = $this->di->getShared('db');
  22. // This method also requires an input filtering service
  23. $filter = $this->di->get('filter');
  24. }
  25. }
  26. $di = new Di();
  27. // Register a 'db' service in the container
  28. $di->set(
  29. 'db',
  30. function () {
  31. return new Connection(
  32. [
  33. 'host' => 'localhost',
  34. 'username' => 'root',
  35. 'password' => 'secret',
  36. 'dbname' => 'invo',
  37. ]
  38. );
  39. }
  40. );
  41. // Register a 'filter' service in the container
  42. $di->set(
  43. 'filter',
  44. function () {
  45. return new Filter();
  46. }
  47. );
  48. // Register a 'session' service in the container
  49. $di->set(
  50. 'session',
  51. function () {
  52. return new Session();
  53. }
  54. );
  55. // Pass the service container as unique parameter
  56. $some = new SomeComponent($di);
  57. $some->someDbTask();

The component can now simply access the service it requires when it needs it, if it does not require a service it is not even initialized, saving resources. The component is now highly decoupled. For example, we can replace the manner in which connections are created, their behavior or any other aspect of them and that would not affect the component.

Phalcon\Di is a component implementing Dependency Injection and Location of services and it’s itself a container for them.

Since Phalcon is highly decoupled, Phalcon\Di is essential to integrate the different components of the framework. The developer can also use this component to inject dependencies and manage global instances of the different classes used in the application.

Basically, this component implements the Inversion of Control pattern. Applying this, the objects do not receive their dependencies using setters or constructors, but requesting a service dependency injector. This reduces the overall complexity since there is only one way to get the required dependencies within a component.

Additionally, this pattern increases testability in the code, thus making it less prone to errors.

Registering services in the Container

The framework itself or the developer can register services. When a component A requires component B (or an instance of its class) to operate, it can request component B from the container, rather than creating a new instance component B.

This way of working gives us many advantages:

  • We can easily replace a component with one created by ourselves or a third party.
  • We have full control of the object initialization, allowing us to set these objects, as needed before delivering them to components.
  • We can get global instances of components in a structured and unified way.
    Services can be registered using several types of definitions:

Simple Registration

As seen before, there are several ways to register services. These we call simple:

String

This type expects the name of a valid class, returning an object of the specified class, if the class is not loaded it will be instantiated using an auto-loader. This type of definition does not allow to specify arguments for the class constructor or parameters:

  1. <?php
  2. // Return new Phalcon\Http\Request();
  3. $di->set(
  4. 'request',
  5. 'Phalcon\Http\Request'
  6. );

Class instances

This type expects an object. Due to the fact that object does not need to be resolved as it is already an object, one could say that it is not really a dependency injection, however it is useful if you want to force the returned dependency to always be the same object/value:

  1. <?php
  2. use Phalcon\Http\Request;
  3. // Return new Phalcon\Http\Request();
  4. $di->set(
  5. 'request',
  6. new Request()
  7. );

Closures/Anonymous functions

This method offers greater freedom to build the dependency as desired, however, it is difficult to change some of the parameters externally without having to completely change the definition of dependency:

  1. <?php
  2. use Phalcon\Db\Adapter\Pdo\Mysql as PdoMysql;
  3. $di->set(
  4. 'db',
  5. function () {
  6. return new PdoMysql(
  7. [
  8. 'host' => 'localhost',
  9. 'username' => 'root',
  10. 'password' => 'secret',
  11. 'dbname' => 'blog',
  12. ]
  13. );
  14. }
  15. );

Some of the limitations can be overcome by passing additional variables to the closure’s environment:

  1. <?php
  2. use Phalcon\Config;
  3. use Phalcon\Db\Adapter\Pdo\Mysql as PdoMysql;
  4. $config = new Config(
  5. [
  6. 'host' => '127.0.0.1',
  7. 'username' => 'user',
  8. 'password' => 'pass',
  9. 'dbname' => 'my_database',
  10. ]
  11. );
  12. // Using the $config variable in the current scope
  13. $di->set(
  14. 'db',
  15. function () use ($config) {
  16. return new PdoMysql(
  17. [
  18. 'host' => $config->host,
  19. 'username' => $config->username,
  20. 'password' => $config->password,
  21. 'dbname' => $config->name,
  22. ]
  23. );
  24. }
  25. );

You can also access other DI services using the get() method:

  1. <?php
  2. use Phalcon\Config;
  3. use Phalcon\Db\Adapter\Pdo\Mysql as PdoMysql;
  4. $di->set(
  5. 'config',
  6. function () {
  7. return new Config(
  8. [
  9. 'host' => '127.0.0.1',
  10. 'username' => 'user',
  11. 'password' => 'pass',
  12. 'dbname' => 'my_database',
  13. ]
  14. );
  15. }
  16. );
  17. // Using the 'config' service from the DI
  18. $di->set(
  19. 'db',
  20. function () {
  21. $config = $this->get('config');
  22. return new PdoMysql(
  23. [
  24. 'host' => $config->host,
  25. 'username' => $config->username,
  26. 'password' => $config->password,
  27. 'dbname' => $config->name,
  28. ]
  29. );
  30. }
  31. );

Complex Registration

If it is required to change the definition of a service without instantiating/resolving the service, then, we need to define the services using the array syntax. Define a service using an array definition can be a little more verbose:

  1. <?php
  2. use Phalcon\Logger\Adapter\File as LoggerFile;
  3. // Register a service 'logger' with a class name and its parameters
  4. $di->set(
  5. 'logger',
  6. [
  7. 'className' => 'Phalcon\Logger\Adapter\File',
  8. 'arguments' => [
  9. [
  10. 'type' => 'parameter',
  11. 'value' => '../apps/logs/error.log',
  12. ]
  13. ]
  14. ]
  15. );
  16. // Using an anonymous function
  17. $di->set(
  18. 'logger',
  19. function () {
  20. return new LoggerFile('../apps/logs/error.log');
  21. }
  22. );

Both service registrations above produce the same result. The array definition however, allows for alteration of the service parameters if needed:

  1. <?php
  2. // Change the service class name
  3. $di
  4. ->getService('logger')
  5. ->setClassName('MyCustomLogger');
  6. // Change the first parameter without instantiating the logger
  7. $di
  8. ->getService('logger')
  9. ->setParameter(
  10. 0,
  11. [
  12. 'type' => 'parameter',
  13. 'value' => '../apps/logs/error.log',
  14. ]
  15. );

In addition by using the array syntax you can use three types of dependency injection:

Constructor Injection

This injection type passes the dependencies/arguments to the class constructor. Let’s pretend we have the following component:

  1. <?php
  2. namespace SomeApp;
  3. use Phalcon\Http\Response;
  4. class SomeComponent
  5. {
  6. /**
  7. * @var Response
  8. */
  9. protected $response;
  10. protected $someFlag;
  11. public function __construct(Response $response, $someFlag)
  12. {
  13. $this->response = $response;
  14. $this->someFlag = $someFlag;
  15. }
  16. }

The service can be registered this way:

  1. <?php
  2. $di->set(
  3. 'response',
  4. [
  5. 'className' => 'Phalcon\Http\Response'
  6. ]
  7. );
  8. $di->set(
  9. 'someComponent',
  10. [
  11. 'className' => 'SomeApp\SomeComponent',
  12. 'arguments' => [
  13. [
  14. 'type' => 'service',
  15. 'name' => 'response',
  16. ],
  17. [
  18. 'type' => 'parameter',
  19. 'value' => true,
  20. ],
  21. ]
  22. ]
  23. );

The service ‘response’ (Phalcon\Http\Response) is resolved to be passed as the first argument of the constructor,while the second is a boolean value (true) that is passed as it is.

Setter Injection

Classes may have setters to inject optional dependencies, our previous class can be changed to accept the dependencies with setters:

  1. <?php
  2. namespace SomeApp;
  3. use Phalcon\Http\Response;
  4. class SomeComponent
  5. {
  6. /**
  7. * @var Response
  8. */
  9. protected $response;
  10. protected $someFlag;
  11. public function setResponse(Response $response)
  12. {
  13. $this->response = $response;
  14. }
  15. public function setFlag($someFlag)
  16. {
  17. $this->someFlag = $someFlag;
  18. }
  19. }

A service with setter injection can be registered as follows:

  1. <?php
  2. $di->set(
  3. 'response',
  4. [
  5. 'className' => 'Phalcon\Http\Response',
  6. ]
  7. );
  8. $di->set(
  9. 'someComponent',
  10. [
  11. 'className' => 'SomeApp\SomeComponent',
  12. 'calls' => [
  13. [
  14. 'method' => 'setResponse',
  15. 'arguments' => [
  16. [
  17. 'type' => 'service',
  18. 'name' => 'response',
  19. ]
  20. ]
  21. ],
  22. [
  23. 'method' => 'setFlag',
  24. 'arguments' => [
  25. [
  26. 'type' => 'parameter',
  27. 'value' => true,
  28. ]
  29. ]
  30. ]
  31. ]
  32. ]
  33. );

Properties Injection

A less common strategy is to inject dependencies or parameters directly into public attributes of the class:

  1. <?php
  2. namespace SomeApp;
  3. use Phalcon\Http\Response;
  4. class SomeComponent
  5. {
  6. /**
  7. * @var Response
  8. */
  9. public $response;
  10. public $someFlag;
  11. }

A service with properties injection can be registered as follows:

  1. <?php
  2. $di->set(
  3. 'response',
  4. [
  5. 'className' => 'Phalcon\Http\Response',
  6. ]
  7. );
  8. $di->set(
  9. 'someComponent',
  10. [
  11. 'className' => 'SomeApp\SomeComponent',
  12. 'properties' => [
  13. [
  14. 'name' => 'response',
  15. 'value' => [
  16. 'type' => 'service',
  17. 'name' => 'response',
  18. ],
  19. ],
  20. [
  21. 'name' => 'someFlag',
  22. 'value' => [
  23. 'type' => 'parameter',
  24. 'value' => true,
  25. ],
  26. ]
  27. ]
  28. ]
  29. );

Supported parameter types include the following:

TypeDescriptionExample
parameterRepresents a literal value to be passed as parameterphp['type' => 'parameter', 'value' => 1234]
serviceRepresents another service in the service containerphp['type' => 'service', 'name' => 'request']
instanceRepresents an object that must be built dynamicallyphp['type' => 'instance', 'className' => 'DateTime', 'arguments' => ['now']]

Resolving a service whose definition is complex may be slightly slower than simple definitions seen previously. However,these provide a more robust approach to define and inject services.

Mixing different types of definitions is allowed, everyone can decide what is the most appropriate way to register the servicesaccording to the application needs.

Array Syntax

The array syntax is also allowed to register services:

  1. <?php
  2. use Phalcon\Di;
  3. use Phalcon\Http\Request;
  4. // Create the Dependency Injector Container
  5. $di = new Di();
  6. // By its class name
  7. $di['request'] = 'Phalcon\Http\Request';
  8. // Using an anonymous function, the instance will be lazy loaded
  9. $di['request'] = function () {
  10. return new Request();
  11. };
  12. // Registering an instance directly
  13. $di['request'] = new Request();
  14. // Using an array definition
  15. $di['request'] = [
  16. 'className' => 'Phalcon\Http\Request',
  17. ];

In the examples above, when the framework needs to access the request data, it will ask for the service identified as ‘request’ in the container. The container in turn will return an instance of the required service. A developer might eventually replace a component when he/she needs.

Each of the methods (demonstrated in the examples above) used to set/register a service has advantages and disadvantages. It is up to the developer and the particular requirements that will designate which one is used.

Setting a service by a string is simple, but lacks flexibility. Setting services using an array offers a lot more flexibility, but makes the code more complicated. The lambda function is a good balance between the two, but could lead to more maintenance than one would expect.

Phalcon\Di offers lazy loading for every service it stores. Unless the developer chooses to instantiate an object directly and store it in the container, any object stored in it (via array, string, etc.) will be lazy loaded i.e. instantiated only when requested.

Loading services from YAML files

This feature will let you set your services in yaml files or just in plain php. For example you can load services using a yaml file like this:

  1. config:
  2. className: \Phalcon\Config
  3. shared: true
  1. <?php
  2. use Phalcon\Di;
  3. $di = new Di();
  4. $di->loadFromYaml('services.yml');
  5. $di->get('config'); // will properly return config service

This approach requires that the module Yaml be installed. Please refer to this for more information.

Resolving Services

Obtaining a service from the container is a matter of simply calling the ‘get’ method. A new instance of the service will be returned:

  1. $request = $di->get('request');

Or by calling through the magic method:

  1. $request = $di->getRequest();

Or using the array-access syntax:

  1. $request = $di['request'];

Arguments can be passed to the constructor by adding an array parameter to the method ‘get’:

  1. <?php
  2. // new MyComponent('some-parameter', 'other')
  3. $component = $di->get(
  4. 'MyComponent',
  5. [
  6. 'some-parameter',
  7. 'other',
  8. ]
  9. );

Events

Phalcon\Di is able to send events to an EventsManager if it is present. Events are triggered using the type ‘di’. Some events when returning boolean false could stop the active operation.The following events are supported:

Event NameTriggeredCan stop operation?Triggered on
beforeServiceResolveTriggered before resolve service. Listeners receive the service name and the parameters passed to it.NoListeners
afterServiceResolveTriggered after resolve service. Listeners receive the service name, instance, and the parameters passed to it.NoListeners

Shared services

Services can be registered as ‘shared’ services this means that they always will act as singletons. Once the service is resolved for the first time the same instance of it is returned every time a consumer retrieve the service from the container:

  1. <?php
  2. use Phalcon\Session\Adapter\Files as SessionFiles;
  3. // Register the session service as 'always shared'
  4. $di->setShared(
  5. 'session',
  6. function () {
  7. $session = new SessionFiles();
  8. $session->start();
  9. return $session;
  10. }
  11. );
  12. // Locates the service for the first time
  13. $session = $di->get('session');
  14. // Returns the first instantiated object
  15. $session = $di->getSession();

An alternative way to register shared services is to pass ‘true’ as third parameter of ‘set’:

  1. <?php
  2. // Register the session service as 'always shared'
  3. $di->set(
  4. 'session',
  5. function () {
  6. // ...
  7. },
  8. true
  9. );

If a service isn’t registered as shared and you want to be sure that a shared instance will be accessed every time the service is obtained from the DI, you can use the ‘getShared’ method:

  1. $request = $di->getShared('request');

Manipulating services individually

Once a service is registered in the service container, you can retrieve it to manipulate it individually:

  1. <?php
  2. use Phalcon\Http\Request;
  3. // Register the 'request' service
  4. $di->set('request', 'Phalcon\Http\Request');
  5. // Get the service
  6. $requestService = $di->getService('request');
  7. // Change its definition
  8. $requestService->setDefinition(
  9. function () {
  10. return new Request();
  11. }
  12. );
  13. // Change it to shared
  14. $requestService->setShared(true);
  15. // Resolve the service (return a Phalcon\Http\Request instance)
  16. $request = $requestService->resolve();

Instantiating classes via the Service Container

When you request a service to the service container, if it can’t find out a service with the same name it’ll try to load a class with the same name. With this behavior we can replace any class by another simply by registering a service with its name:

  1. <?php
  2. // Register a controller as a service
  3. $di->set(
  4. 'IndexController',
  5. function () {
  6. $component = new Component();
  7. return $component;
  8. },
  9. true
  10. );
  11. // Register a controller as a service
  12. $di->set(
  13. 'MyOtherComponent',
  14. function () {
  15. // Actually returns another component
  16. $component = new AnotherComponent();
  17. return $component;
  18. }
  19. );
  20. // Create an instance via the service container
  21. $myComponent = $di->get('MyOtherComponent');

You can take advantage of this, always instantiating your classes via the service container (even if they aren’t registered as services). The DI will fallback to a valid autoloader to finally load the class. By doing this, you can easily replace any class in the future by implementing a definition for it.

Automatic Injecting of the DI itself

If a class or component requires the DI itself to locate services, the DI can automatically inject itself to the instances it creates, to do this, you need to implement the Phalcon\Di\InjectionAwareInterface in your classes:

  1. <?php
  2. use Phalcon\DiInterface;
  3. use Phalcon\Di\InjectionAwareInterface;
  4. class MyClass implements InjectionAwareInterface
  5. {
  6. /**
  7. * @var DiInterface
  8. */
  9. protected $di;
  10. public function setDi(DiInterface $di)
  11. {
  12. $this->di = $di;
  13. }
  14. public function getDi()
  15. {
  16. return $this->di;
  17. }
  18. }

Then once the service is resolved, the $di will be passed to setDi() automatically:

  1. <?php
  2. // Register the service
  3. $di->set('myClass', 'MyClass');
  4. // Resolve the service (NOTE: $myClass->setDi($di) is automatically called)
  5. $myClass = $di->get('myClass');

Organizing services in files

You can better organize your application by moving the service registration to individual files instead ofdoing everything in the application’s bootstrap:

  1. <?php
  2. $di->set(
  3. 'router',
  4. function () {
  5. return include '../app/config/routes.php';
  6. }
  7. );

Then in the file ('../app/config/routes.php') return the object resolved:

  1. <?php
  2. $router = new MyRouter();
  3. $router->post('/login');
  4. return $router;

Accessing the DI in a static way

If needed you can access the latest DI created in a static function in the following way:

  1. <?php
  2. use Phalcon\Di;
  3. class SomeComponent
  4. {
  5. public static function someMethod()
  6. {
  7. // Get the session service
  8. $session = Di::getDefault()->getSession();
  9. }
  10. }

Service Providers

Using the ServiceProviderInterface you now register services by context. You can move all your $di->set() calls to classes like this:

  1. <?php
  2. use Phalcon\Di\ServiceProviderInterface;
  3. use Phalcon\DiInterface;
  4. use Phalcon\Di;
  5. use Phalcon\Config\Adapter\Ini;
  6. class SomeServiceProvider implements ServiceProviderInterface
  7. {
  8. public function register(DiInterface $di)
  9. {
  10. $di->set(
  11. 'config',
  12. function () {
  13. return new Ini('config.ini');
  14. }
  15. );
  16. }
  17. }
  18. $di = new Di();
  19. $di->register(new SomeServiceProvider());
  20. var_dump($di->get('config')); // will return properly our config

Factory Default DI

Although the decoupled character of Phalcon offers us great freedom and flexibility, maybe we just simply want to use it as a full-stack framework. To achieve this, the framework provides a variant of Phalcon\Di called Phalcon\Di\FactoryDefault. This class automatically registers the appropriate services bundled with the framework to act as full-stack.

  1. <?php
  2. use Phalcon\Di\FactoryDefault;
  3. $di = new FactoryDefault();

Service Name Conventions

Although you can register services with the names you want, Phalcon has a several naming conventions that allow it to get the the correct (built-in) service when you need it.

Service NameDescriptionDefaultShared
assetsAssets ManagerPhalcon\Assets\ManagerYes
annotationsAnnotations ParserPhalcon\Annotations\Adapter\MemoryYes
cookiesHTTP Cookies Management ServicePhalcon\Http\Response\CookiesYes
cryptEncrypt/Decrypt dataPhalcon\CryptYes
dbLow-Level Database Connection ServicePhalcon\DbYes
dispatcherControllers Dispatching ServicePhalcon\Mvc\DispatcherYes
eventsManagerEvents Management ServicePhalcon\Events\ManagerYes
escaperContextual EscapingPhalcon\EscaperYes
flashFlash Messaging ServicePhalcon\Flash\DirectYes
flashSessionFlash Session Messaging ServicePhalcon\Flash\SessionYes
filterInput Filtering ServicePhalcon\FilterYes
modelsCacheCache backend for models cacheNoneNo
modelsManagerModels Management ServicePhalcon\Mvc\Model\ManagerYes
modelsMetadataModels Meta-Data ServicePhalcon\Mvc\Model\MetaData\MemoryYes
requestHTTP Request Environment ServicePhalcon\Http\RequestYes
responseHTTP Response Environment ServicePhalcon\Http\ResponseYes
routerRouting ServicePhalcon\Mvc\RouterYes
securitySecurity helpersPhalcon\SecurityYes
sessionSession ServicePhalcon\Session\Adapter\FilesYes
sessionBagSession Bag servicePhalcon\Session\BagYes
tagHTML generation helpersPhalcon\TagYes
transactionManagerModels Transaction Manager ServicePhalcon\Mvc\Model\Transaction\ManagerYes
urlURL Generator ServicePhalcon\Mvc\UrlYes
viewsCacheCache backend for views fragmentsNoneNo

Implementing your own DI

The Phalcon\DiInterface interface must be implemented to create your own DI replacing the one provided by Phalcon or extend the current one.