Skip to content

Phalcon di

NOTE

All classes are prefixed with Phalcon

Di

Source on GitHub

  • Namespace

    • Phalcon
  • Uses

    • Phalcon\Config\Adapter\Php
    • Phalcon\Config\Adapter\Yaml
    • Phalcon\Config\ConfigInterface
    • Phalcon\Di\DiInterface
    • Phalcon\Di\Exception
    • Phalcon\Di\Exception\ServiceResolutionException
    • Phalcon\Di\InitializationAwareInterface
    • Phalcon\Di\InjectionAwareInterface
    • Phalcon\Di\Service
    • Phalcon\Di\ServiceInterface
    • Phalcon\Di\ServiceProviderInterface
    • Phalcon\Events\ManagerInterface
  • Extends

  • Implements

    • DiInterface

Phalcon\Di is a component that implements Dependency Injection/Service 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.

use Phalcon\Di;
use Phalcon\Http\Request;

$di = new Di();

// Using a string definition
$di->set("request", Request::class, true);

// Using an anonymous function
$di->setShared(
    "request",
    function () {
        return new Request();
    }
);

$request = $di->getRequest();

Properties

/**
 * List of registered services
 *
 * @var ServiceInterface[]
 */
protected $services;

/**
 * List of shared instances
 *
 * @var array
 */
protected $sharedInstances;

/**
 * Events Manager
 *
 * @var ManagerInterface|null
 */
protected $eventsManager;

/**
 * Latest DI build
 *
 * @var DiInterface|null
 */
protected $static $_default;

Methods

public function __call( string $method, array $arguments = [] ): mixed | null;
Magic method to get or set services using setters/getters

public function __construct();
Phalcon\Di constructor

public function attempt( string $name, mixed $definition, bool $shared = bool ): ServiceInterface | bool;
Attempts to register a service in the services container Only is successful if a service hasn't been registered previously with the same name

public function get( string $name, mixed $parameters = null ): mixed;
Resolves the service based on its configuration

public static function getDefault(): DiInterface | null;
Return the latest DI created

public function getInternalEventsManager(): ManagerInterface | null;
Returns the internal event manager

public function getRaw( string $name ): mixed;
Returns a service definition without resolving

public function getService( string $name ): ServiceInterface;
Returns a Phalcon\Di\Service instance

public function getServices(): ServiceInterface[];
Return the services registered in the DI

public function getShared( string $name, mixed $parameters = null ): mixed;
Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance

public function has( string $name ): bool;
Check whether the DI contains a service by a name

public function loadFromPhp( string $filePath ): void;
Loads services from a php config file.

$di->loadFromPhp("path/services.php");

And the services can be specified in the file as:

return [
     'myComponent' => [
         'className' => '\Acme\Components\MyComponent',
         'shared' => true,
     ],
     'group' => [
         'className' => '\Acme\Group',
         'arguments' => [
             [
                 'type' => 'service',
                 'service' => 'myComponent',
             ],
         ],
     ],
     'user' => [
         'className' => '\Acme\User',
     ],
];

@link https://docs.phalcon.io/en/latest/reference/di.html

public function loadFromYaml( string $filePath, array $callbacks = null ): void;
Loads services from a yaml file.

$di->loadFromYaml(
    "path/services.yaml",
    [
        "!approot" => function ($value) {
            return dirname(__DIR__) . $value;
        }
    ]
);

And the services can be specified in the file as:

myComponent:
    className: \Acme\Components\MyComponent
    shared: true

group:
    className: \Acme\Group
    arguments:
        - type: service
          name: myComponent

user:
   className: \Acme\User

@link https://docs.phalcon.io/en/latest/reference/di.html

public function offsetExists( mixed $name ): bool;
Check if a service is registered using the array syntax

public function offsetGet( mixed $name ): mixed;
Allows to obtain a shared service using the array syntax

var_dump($di["request"]);

public function offsetSet( mixed $name, mixed $definition ): void;
Allows to register a shared service using the array syntax

$di["request"] = new \Phalcon\Http\Request();

public function offsetUnset( mixed $name ): void;
Removes a service from the services container using the array syntax

public function register( ServiceProviderInterface $provider ): void;
Registers a service provider.

use Phalcon\Di\DiInterface;
use Phalcon\Di\ServiceProviderInterface;

class SomeServiceProvider implements ServiceProviderInterface
{
    public function register(DiInterface $di)
    {
        $di->setShared(
            'service',
            function () {
                // ...
            }
        );
    }
}

public function remove( string $name ): void;
Removes a service in the services container It also removes any shared instance created for the service

public static function reset(): void;
Resets the internal default DI

public function set( string $name, mixed $definition, bool $shared = bool ): ServiceInterface;
Registers a service in the services container

public static function setDefault( DiInterface $container ): void;
Set a default dependency injection container to be obtained into static methods

public function setInternalEventsManager( ManagerInterface $eventsManager );
Sets the internal event manager

public function setService( string $name, ServiceInterface $rawDefinition ): ServiceInterface;
Sets a service using a raw Phalcon\Di\Service definition

public function setShared( string $name, mixed $definition ): ServiceInterface;
Registers an "always shared" service in the services container

protected function loadFromConfig( ConfigInterface $config ): void;
Loads services from a Config object.

Di\AbstractInjectionAware Abstract

Source on GitHub

  • Namespace

    • Phalcon\Di
  • Uses

  • Extends

  • Implements

    • InjectionAwareInterface

This abstract class offers common access to the DI in a class

Properties

/**
 * Dependency Injector
 *
 * @var DiInterface
 */
protected $container;

Methods

public function getDI(): DiInterface;
Returns the internal dependency injector

public function setDI( DiInterface $container ): void;
Sets the dependency injector

Di\DiInterface Interface

Source on GitHub

  • Namespace

    • Phalcon\Di
  • Uses

    • ArrayAccess
  • Extends

    ArrayAccess

  • Implements

Interface for Phalcon\Di

Methods

public function attempt( string $name, mixed $definition, bool $shared = bool ): ServiceInterface | bool;
Attempts to register a service in the services container Only is successful if a service hasn't been registered previously with the same name

public function get( string $name, mixed $parameters = null ): mixed;
Resolves the service based on its configuration

public static function getDefault(): DiInterface | null;
Return the last DI created

public function getRaw( string $name ): mixed;
Returns a service definition without resolving

public function getService( string $name ): ServiceInterface;
Returns the corresponding Phalcon\Di\Service instance for a service

public function getServices(): ServiceInterface[];
Return the services registered in the DI

public function getShared( string $name, mixed $parameters = null ): mixed;
Returns a shared service based on their configuration

public function has( string $name ): bool;
Check whether the DI contains a service by a name

public function remove( string $name ): void;
Removes a service in the services container

public static function reset(): void;
Resets the internal default DI

public function set( string $name, mixed $definition, bool $shared = bool ): ServiceInterface;
Registers a service in the services container

public static function setDefault( DiInterface $container ): void;
Set a default dependency injection container to be obtained into static methods

public function setService( string $name, ServiceInterface $rawDefinition ): ServiceInterface;
Sets a service using a raw Phalcon\Di\Service definition

public function setShared( string $name, mixed $definition ): ServiceInterface;
Registers an "always shared" service in the services container

Di\Exception

Source on GitHub

  • Namespace

    • Phalcon\Di
  • Uses

  • Extends

    \Exception

  • Implements

Exceptions thrown in Phalcon\Di will use this class

Di\Exception\ServiceResolutionException

Source on GitHub

  • Namespace

    • Phalcon\Di\Exception
  • Uses

  • Extends

    \Phalcon\Di\Exception

  • Implements

Phalcon\Di\Exception\ServiceResolutionException

Di\FactoryDefault

Source on GitHub

  • Namespace

    • Phalcon\Di
  • Uses

    • Phalcon\Filter\FilterFactory
  • Extends

    \Phalcon\Di\Di

  • Implements

This is a variant of the standard Phalcon\Di. By default it automatically registers all the services provided by the framework. Thanks to this, the developer does not need to register each service individually providing a full stack framework

Methods

public function __construct();
Phalcon\Di\FactoryDefault constructor

Di\FactoryDefault\Cli

Source on GitHub

  • Namespace

    • Phalcon\Di\FactoryDefault
  • Uses

    • Phalcon\Di\FactoryDefault
    • Phalcon\Di\Service
    • Phalcon\Filter\FilterFactory
  • Extends

    FactoryDefault

  • Implements

Phalcon\Di\FactoryDefault\Cli

This is a variant of the standard Phalcon\Di. By default it automatically registers all the services provided by the framework. Thanks to this, the developer does not need to register each service individually. This class is specially suitable for CLI applications

Methods

public function __construct();
Phalcon\Di\FactoryDefault\Cli constructor

Di\Injectable Abstract

Source on GitHub

  • Namespace

    • Phalcon\Di
  • Uses

    • Phalcon\Di\Di
    • Phalcon\Session\BagInterface
    • stdClass
  • Extends

    stdClass

  • Implements

    • InjectionAwareInterface

This class allows to access services in the services container by just only accessing a public property with the same name of a registered service

Properties

/**
 * Dependency Injector
 *
 * @var DiInterface
 */
protected $container;

Methods

public function __get( string $propertyName ): mixed | null;
Magic method __get

public function __isset( string $name ): bool;
Magic method __isset

public function getDI(): DiInterface;
Returns the internal dependency injector

public function setDI( DiInterface $container ): void;
Sets the dependency injector

Di\InjectionAwareInterface Interface

Source on GitHub

  • Namespace

    • Phalcon\Di
  • Uses

  • Extends

  • Implements

This interface must be implemented in those classes that uses internally the Phalcon\Di that creates them

Methods

public function getDI(): DiInterface;
Returns the internal dependency injector

public function setDI( DiInterface $container ): void;
Sets the dependency injector

Di\Service

Source on GitHub

  • Namespace

    • Phalcon\Di
  • Uses

    • Closure
    • Phalcon\Di\Exception\ServiceResolutionException
    • Phalcon\Di\Service\Builder
  • Extends

  • Implements

    • ServiceInterface

Represents individually a service in the services container

$service = new \Phalcon\Di\Service(
    "request",
    \Phalcon\Http\Request::class
);

$request = service->resolve();

Properties

/**
 * @var mixed
 */
protected $definition;

/**
 * @var bool
 */
protected $resolved = false;

/**
 * @var bool
 */
protected $shared = false;

//
protected $sharedInstance;

Methods

final public function __construct( mixed $definition, bool $shared = bool );
Phalcon\Di\Service

public function getDefinition(): mixed;
Returns the service definition

public function getParameter( int $position );
Returns a parameter in a specific position

public function isResolved(): bool;
Returns true if the service was resolved

public function isShared(): bool;
Check whether the service is shared or not

public function resolve( mixed $parameters = null, DiInterface $container = null ): mixed;
Resolves the service

public function setDefinition( mixed $definition ): void;
Set the service definition

public function setParameter( int $position, array $parameter ): ServiceInterface;
Changes a parameter in the definition without resolve the service

public function setShared( bool $shared ): void;
Sets if the service is shared or not

public function setSharedInstance( mixed $sharedInstance ): void;
Sets/Resets the shared instance related to the service

Di\Service\Builder

Source on GitHub

  • Namespace

    • Phalcon\Di\Service
  • Uses

    • Phalcon\Di\DiInterface
    • Phalcon\Di\Exception
  • Extends

  • Implements

Phalcon\Di\Service\Builder

This class builds instances based on complex definitions

Methods

public function build( DiInterface $container, array $definition, mixed $parameters = null );
Builds a service using a complex service definition

Di\ServiceInterface Interface

Source on GitHub

  • Namespace

    • Phalcon\Di
  • Uses

  • Extends

  • Implements

Represents a service in the services container

Methods

public function getDefinition(): mixed;
Returns the service definition

public function getParameter( int $position );
Returns a parameter in a specific position

public function isResolved(): bool;
Returns true if the service was resolved

public function isShared(): bool;
Check whether the service is shared or not

public function resolve( mixed $parameters = null, DiInterface $container = null ): mixed;
Resolves the service

public function setDefinition( mixed $definition );
Set the service definition

public function setParameter( int $position, array $parameter ): ServiceInterface;
Changes a parameter in the definition without resolve the service

public function setShared( bool $shared );
Sets if the service is shared or not

Di\ServiceProviderInterface Interface

Source on GitHub

  • Namespace

    • Phalcon\Di
  • Uses

  • Extends

  • Implements

Should be implemented by service providers, or such components, which register a service in the service container.

namespace Acme;

use Phalcon\Di\DiInterface;
use Phalcon\Di\ServiceProviderInterface;

class SomeServiceProvider implements ServiceProviderInterface
{
    public function register(DiInterface $di)
    {
        $di->setShared(
            'service',
            function () {
                // ...
            }
        );
    }
}

Methods

public function register( DiInterface $di ): void;
Registers a service provider.