Sections

Class Phalcon\Di

Source on GitHub

Namespace Phalcon   Uses Phalcon\Config, Phalcon\Di\Service, Phalcon\Di\DiInterface, Phalcon\Di\Exception, Phalcon\Di\Exception\ServiceResolutionException, Phalcon\Config\Adapter\Php, Phalcon\Config\Adapter\Yaml, Phalcon\Di\ServiceInterface, Phalcon\Events\ManagerInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\Di\ServiceProviderInterface   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
 */
protected services;

/**
 * List of shared instances
 */
protected sharedInstances;

/**
 * Events Manager
 *
 * @var ManagerInterface
 */
protected eventsManager;

/**
 * Latest DI build
 */
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(): void;

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;

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 setRaw( 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( Config $config ): void;

Loads services from a Config object.

Abstract Class Phalcon\Di\AbstractInjectionAware

Source on GitHub

Namespace Phalcon\Di   Uses Phalcon\Di, Phalcon\Di\DiInterface, Phalcon\Di\InjectionAwareInterface   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

Interface Phalcon\Di\DiInterface

Source on GitHub

Namespace Phalcon\Di   Uses ArrayAccess, Phalcon\Di\ServiceInterface   Extends ArrayAccess

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 setRaw( 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

Class Phalcon\Di\Exception

Source on GitHub

Namespace Phalcon\Di   Extends \Phalcon\Exception

Exceptions thrown in Phalcon\Di will use this class

Class Phalcon\Di\Exception\ServiceResolutionException

Source on GitHub

Namespace Phalcon\Di\Exception   Uses Phalcon\Di\Exception\ServiceResolutionException   Extends \Phalcon\Di\Exception

Phalcon\Di\Exception\ServiceResolutionException

Class Phalcon\Di\FactoryDefault

Source on GitHub

Namespace Phalcon\Di   Uses Phalcon\Filter\FilterFactory   Extends \Phalcon\Di

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(): void;

Phalcon\Di\FactoryDefault constructor

Class Phalcon\Di\FactoryDefault\Cli

Source on GitHub

Namespace Phalcon\Di\FactoryDefault   Uses Phalcon\Di\FactoryDefault, Phalcon\Di\Service, Phalcon\Filter\FilterFactory   Extends FactoryDefault

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(): void;

Phalcon\Di\FactoryDefault\Cli constructor

Abstract Class Phalcon\Di\Injectable

Source on GitHub

Namespace Phalcon\Di   Uses Phalcon\Di, Phalcon\Di\DiInterface, Phalcon\Events\ManagerInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface, Phalcon\Di\Exception, Phalcon\Session\BagInterface   Implements InjectionAwareInterface, EventsAwareInterface

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

@property \Phalcon\Mvc\Dispatcher \Phalcon\Mvc\DispatcherInterface $dispatcher @property \Phalcon\Mvc\Router \Phalcon\Mvc\RouterInterface $router @property \Phalcon\Url \Phalcon\Url\UrlInterface $url @property \Phalcon\Http\Request \Phalcon\Http\RequestInterface $request @property \Phalcon\Http\Response \Phalcon\Http\ResponseInterface $response @property \Phalcon\Http\Response\Cookies \Phalcon\Http\Response\CookiesInterface $cookies @property \Phalcon\Filter $filter @property \Phalcon\Flash\Direct $flash @property \Phalcon\Flash\Session $flashSession @property \Phalcon\Session\ManagerInterface $session @property \Phalcon\Events\Manager \Phalcon\Events\ManagerInterface $eventsManager @property \Phalcon\Db\Adapter\AdapterInterface $db @property \Phalcon\Security $security @property \Phalcon\Crypt \Phalcon\CryptInterface $crypt @property \Phalcon\Tag $tag @property \Phalcon\Escaper \Phalcon\Escaper\EscaperInterface $escaper @property \Phalcon\Annotations\Adapter\Memory \Phalcon\Annotations\Adapter $annotations @property \Phalcon\Mvc\Model\Manager \Phalcon\Mvc\Model\ManagerInterface $modelsManager @property \Phalcon\Mvc\Model\MetaData\Memory \Phalcon\Mvc\Model\MetadataInterface $modelsMetadata @property \Phalcon\Mvc\Model\Transaction\Manager \Phalcon\Mvc\Model\Transaction\ManagerInterface $transactionManager @property \Phalcon\Assets\Manager $assets @property \Phalcon\Di \Phalcon\Di\DiInterface $di @property \Phalcon\Session\Bag \Phalcon\Session\BagInterface $persistent @property \Phalcon\Mvc\View \Phalcon\Mvc\ViewInterface $view

Properties

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

/**
 * Events Manager
 *
 * @var \Phalcon\Events\ManagerInterface
 */
protected eventsManager;

Methods

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

Magic method __get

public function getDI(): DiInterface;

Returns the internal dependency injector

public function getEventsManager(): ManagerInterface;

Returns the internal event manager

public function setDI( DiInterface $container ): void;

Sets the dependency injector

public function setEventsManager( ManagerInterface $eventsManager ): void;

Sets the event manager

Interface Phalcon\Di\InjectionAwareInterface

Source on GitHub

Namespace Phalcon\Di   Uses Phalcon\Di\DiInterface

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

Class Phalcon\Di\Service

Source on GitHub

Namespace Phalcon\Di   Uses Closure, Phalcon\Di\DiInterface, Phalcon\Di\Exception, Phalcon\Di\Exception\ServiceResolutionException, Phalcon\Di\ServiceInterface, Phalcon\Di\Service\Builder   Implements ServiceInterface

Represents individually a service in the services container

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

$request = service->resolve();

Properties

//
protected definition;

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

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

//
protected sharedInstance;

Methods

final public function __construct( mixed $definition, bool $shared = bool ): void;

Phalcon\Di\Service

public function getDefinition(): mixed;

Returns the service definition

public function getParameter( int $position );

Returns a parameter in a specific position

@return array

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

Class Phalcon\Di\Service\Builder

Source on GitHub

Namespace Phalcon\Di\Service   Uses Phalcon\Di\DiInterface, Phalcon\Di\Exception

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

@return mixed

Interface Phalcon\Di\ServiceInterface

Source on GitHub

Namespace Phalcon\Di   Uses Phalcon\Di\DiInterface

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

@return array

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

Interface Phalcon\Di\ServiceProviderInterface

Source on GitHub

Namespace Phalcon\Di   Uses Phalcon\Di\DiInterface

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.