Namespace | Phalcon\Di | Implements | InjectionAwareInterface |
Esta clase abstracta ofrece acceso común al DI en una clase
/**
* Dependency Injector
*
* @var DiInterface
*/
protected container;
public function getDI(): DiInterface;
Devuelve el inyector de dependencias interno
public function setDI( DiInterface $container ): void;
Configura el inyector de dependencia
Namespace | Phalcon\Di | Uses | Phalcon\Di\Service, Phalcon\Di\DiInterface, Phalcon\Di\Exception, Phalcon\Di\Exception\ServiceResolutionException, Phalcon\Config\Adapter\Php, Phalcon\Config\Adapter\Yaml, Phalcon\Config\ConfigInterface, Phalcon\Di\ServiceInterface, Phalcon\Events\ManagerInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\Di\ServiceProviderInterface | Implements | DiInterface |
Phalcon\Di\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\Di is essential to integrate the different components of the framework. El desarrollador puede usar también este componente para inyectar dependencias y gestionar instancias globales de las diferentes clases usadas en la aplicación.
Básicamente, este componente implementa el patrón Inversión de Control
. Aplicando esto, los objetos no reciben sus dependencias usando setters o constructores, sino solicitando un servicio de inyección de dependencias. Esto reduce la complejidad general, ya que sólo hay una forma de obtener las dependencias requeridas desde un componente.
Además, este patrón incrementa la testabilidad en el código, ya que lo hace menos propenso a errores.
use Phalcon\Di\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();
/**
* 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;
public function __call( string $method, array $arguments = [] ): mixed | null;
Método mágico para obtener o establecer servicios usando setters/getters
public function __construct();
Phalcon\Di\Di constructor
public function attempt( string $name, mixed $definition, bool $shared = bool ): ServiceInterface | bool;
Intenta registrar un servicio en el contenedor de servicios Sólo será exitoso si no ha sido registrado ningún servicio previamente con el mismo nombre
public function get( string $name, mixed $parameters = null ): mixed;
Resuelve el servicio según su configuración
public static function getDefault(): DiInterface | null;
Devuelve el último DI creado
public function getInternalEventsManager(): ManagerInterface | null;
Devuelve el administrador de eventos interno
public function getRaw( string $name ): mixed;
Devuelve una definición de servicio sin resolver
public function getService( string $name ): ServiceInterface;
Devuelve una instancia Phalcon\Di\Service
public function getServices(): ServiceInterface[];
Devuelve los servicios registrados en el DI
public function getShared( string $name, mixed $parameters = null ): mixed;
Resuelve un servicio, el servicio resuelto se almacena en el DI, las siguientes peticiones de este servicio devolverán la misma instancia
public function has( string $name ): bool;
Comprueba si el DI contiene un servicio por un nombre
public function loadFromPhp( string $filePath ): void;
Carga servicios desde un fichero de configuración php.
$di->loadFromPhp("path/services.php");
Y los servicios se pueden especificar en un fichero como:
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;
Carga servicios desde un fichero yaml.
$di->loadFromYaml(
"path/services.yaml",
[
"!approot" => function ($value) {
return dirname(__DIR__) . $value;
}
]
);
Y los servicios se pueden especificar en un fichero como:
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;
Comprueba si un servicio está registrando usando la sintaxis vector
public function offsetGet( mixed $name ): mixed;
Permite obtener un servicio compartido usando la sintaxis vector
var_dump($di["request"]);
public function offsetSet( mixed $name, mixed $definition ): void;
Permite registrar un servicio compartido usando la sintaxis vector
$di["request"] = new \Phalcon\Http\Request();
public function offsetUnset( mixed $name ): void;
Elimina un servicio del contenedor de servicios usando la sintaxis vector
public function register( ServiceProviderInterface $provider ): void;
Registra un proveedor de servicios.
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;
Elimina un servicio en el contenedor de servicios También elimina cualquier instancia compartida creada para el servicio
public static function reset(): void;
Resetea el DI interno predeterminado
public function set( string $name, mixed $definition, bool $shared = bool ): ServiceInterface;
Registra un servicio en el contenedor de servicios
public static function setDefault( DiInterface $container ): void;
Establece un contenedor de inyección de dependencias predeterminado para ser obtenido en métodos estáticos
public function setInternalEventsManager( ManagerInterface $eventsManager );
Establece el gestor de eventos interno
public function setService( string $name, ServiceInterface $rawDefinition ): ServiceInterface;
Establece un servicio usando una definición Phalcon\Di\Service
sin procesar
public function setShared( string $name, mixed $definition ): ServiceInterface;
Registra un servicio “siempre compartido” en el contenedor de servicios
protected function loadFromConfig( ConfigInterface $config ): void;
Carga servicios desde un objeto Config
.
Namespace | Phalcon\Di | Uses | ArrayAccess | Extends | ArrayAccess |
Interface for Phalcon\Di\Di
public function attempt( string $name, mixed $definition, bool $shared = bool ): ServiceInterface | bool;
Intenta registrar un servicio en el contenedor de servicios Sólo será exitoso si no ha sido registrado ningún servicio previamente con el mismo nombre
public function get( string $name, mixed $parameters = null ): mixed;
Resuelve el servicio según su configuración
public static function getDefault(): DiInterface | null;
Devuelve el último DI creado
public function getRaw( string $name ): mixed;
Devuelve una definición de servicio sin resolver
public function getService( string $name ): ServiceInterface;
Devuelve la correspondiente instancia Phalcon\Di\Service para un servicio
public function getServices(): ServiceInterface[];
Devuelve los servicios registrados en el DI
public function getShared( string $name, mixed $parameters = null ): mixed;
Devuelve un servicio compartido según su configuración
public function has( string $name ): bool;
Comprueba si el DI contiene un servicio por un nombre
public function remove( string $name ): void;
Devuelve un servicio del contenedor de servicios
public static function reset(): void;
Resetea el DI interno predeterminado
public function set( string $name, mixed $definition, bool $shared = bool ): ServiceInterface;
Registra un servicio en el contenedor de servicios
public static function setDefault( DiInterface $container ): void;
Establece un contenedor de inyección de dependencias predeterminado para ser obtenido en métodos estáticos
public function setService( string $name, ServiceInterface $rawDefinition ): ServiceInterface;
Establece un servicio usando una definición Phalcon\Di\Service
sin procesar
public function setShared( string $name, mixed $definition ): ServiceInterface;
Registra un servicio “siempre compartido” en el contenedor de servicios
Namespace | Phalcon\Di | Extends | \Exception |
Las excepciones lanzadas en Phalcon\Di usarán esta clase
Namespace | Phalcon\Di\Exception | Extends | \Phalcon\Di\Exception |
Phalcon\Di\Exception\ServiceResolutionException
Namespace | Phalcon\Di | Uses | Phalcon\Filter\FilterFactory | Extends | \Phalcon\Di\Di |
This is a variant of the standard Phalcon\Di\Di. Por defecto, registra automáticamente todos los servicios proporcionados por el framework. Gracias a esto, el desarrollador no necesita registrar cada servicio individualmente proporcionando un framework de pila completa
public function __construct();
Constructor Phalcon\Di\FactoryDefault
Namespace | Phalcon\Di\FactoryDefault | Uses | Phalcon\Di\FactoryDefault, Phalcon\Di\Service, Phalcon\Filter\FilterFactory | Extends | FactoryDefault |
Phalcon\Di\FactoryDefault\Cli
Esta es una variante del estándar Phalcon\Di. Por defecto, registra automáticamente todos los servicios proporcionados por el framework. Gracias a esto, el desarrollador no necesita registrar cada servicio individualmente. Esta clase es especialmente apropiada para aplicaciones CLI
public function __construct();
Constructor Phalcon\Di\FactoryDefault\Cli
Namespace | Phalcon\Di | Uses | Phalcon\Di\Di, Phalcon\Session\BagInterface | Implements | InjectionAwareInterface |
Esta clase permite acceder a servicios en el contenedor de servicios simplemente accediendo a una propiedad pública con el mismo nombre que el servicio registrado
@property \Phalcon\Mvc\Dispatcher | \Phalcon\Mvc\DispatcherInterface $dispatcher @property \Phalcon\Mvc\Router | \Phalcon\Mvc\RouterInterface $router @property \Phalcon\Mvc\Url | \Phalcon\Mvc\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\Crypt | \Phalcon\Crypt\CryptInterface $crypt @property \Phalcon\Tag $tag @property \Phalcon\Html\Escaper | \Phalcon\Html\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\Di | \Phalcon\Di\Di\DiInterface $di @property \Phalcon\Session\Bag | \Phalcon\Session\BagInterface $persistent @property \Phalcon\Mvc\View | \Phalcon\Mvc\ViewInterface $view |
/**
* Dependency Injector
*
* @var DiInterface|null
*/
protected container;
public function __get( string $propertyName ): mixed | null;
Método mágico __get
public function __isset( string $name ): bool;
Método mágico __isset
public function getDI(): DiInterface;
Devuelve el inyector de dependencias interno
public function setDI( DiInterface $container ): void;
Configura el inyector de dependencia
Namespace | Phalcon\Di |
This interface must be implemented in those classes that uses internally the Phalcon\Di\Di that creates them
public function getDI(): DiInterface;
Devuelve el inyector de dependencias interno
public function setDI( DiInterface $container ): void;
Configura el inyector de dependencia
Namespace | Phalcon\Di | Uses | Closure, Phalcon\Di\Exception\ServiceResolutionException, Phalcon\Di\Service\Builder | Implements | ServiceInterface |
Representa individualmente a un servicio en el contenedor de servicios
$service = new \Phalcon\Di\Service(
"request",
\Phalcon\Http\Request::class
);
$request = service->resolve();
/**
* @var mixed
*/
protected definition;
/**
* @var bool
*/
protected resolved = false;
/**
* @var bool
*/
protected shared = false;
/**
* @var mixed|null
*/
protected sharedInstance;
final public function __construct( mixed $definition, bool $shared = bool );
Phalcon\Di\Service
public function getDefinition(): mixed;
Obtiene la definición del servicio
public function getParameter( int $position );
Obtiene un parámetro en una posición específica
public function isResolved(): bool;
Devuelve true
si se resolvió el servicio
public function isShared(): bool;
Comprueba si el servicio es compartido o no
public function resolve( mixed $parameters = null, DiInterface $container = null ): mixed;
Resuelve el servicio
public function setDefinition( mixed $definition ): void;
Establece la definición del servicio
public function setParameter( int $position, array $parameter ): ServiceInterface;
Cambia un parámetro en la definición sin resolver el servicio
public function setShared( bool $shared ): void;
Establece si el servicio es compartido o no
public function setSharedInstance( mixed $sharedInstance ): void;
Establece/Reestablece la instancia compartida relacionada con el servicio
Namespace | Phalcon\Di\Service | Uses | Phalcon\Di\DiInterface, Phalcon\Di\Exception |
Phalcon\Di\Service\Builder
Esta clase construye instancias según definiciones complejas
public function build( DiInterface $container, array $definition, mixed $parameters = null );
Construye un servicio usando una definición de servicio compleja
Namespace | Phalcon\Di |
Representa un servicio en el contenedor de servicios
public function getDefinition(): mixed;
Obtiene la definición del servicio
public function getParameter( int $position );
Obtiene un parámetro en una posición específica
public function isResolved(): bool;
Devuelve true
si se resolvió el servicio
public function isShared(): bool;
Comprueba si el servicio es compartido o no
public function resolve( mixed $parameters = null, DiInterface $container = null ): mixed;
Resuelve el servicio
public function setDefinition( mixed $definition );
Establece la definición del servicio
public function setParameter( int $position, array $parameter ): ServiceInterface;
Cambia un parámetro en la definición sin resolver el servicio
public function setShared( bool $shared );
Establece si el servicio es compartido o no
Namespace | Phalcon\Di |
Se debería implementar por proveedores de servicio, o aquellos componentes que registran un servicio en el contenedor de servicios.
namespace Acme;
use Phalcon\Di\DiInterface;
use Phalcon\Di\ServiceProviderInterface;
class SomeServiceProvider implements ServiceProviderInterface
{
public function register(DiInterface $di)
{
$di->setShared(
'service',
function () {
// ...
}
);
}
}
public function register( DiInterface $di ): void;
Registra un proveedor de servicios.