Abstract Class Phalcon\Di\AbstractInjectionAware
Código fuente en GitHub
Namespace |
Phalcon\Di |
|
Implements |
InjectionAwareInterface |
Esta clase abstracta ofrece acceso común al DI en una clase
Propiedades
/**
* Dependency Injector
*
* @var DiInterface
*/
protected container;
Métodos
public function getDI(): DiInterface;
Devuelve el inyector de dependencias interno
public function setDI( DiInterface $container ): void;
Configura el inyector de dependencia
Class Phalcon\Di\Di
Código fuente en GitHub
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\InitializationAwareInterface, 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();
Propiedades
/**
* 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 defaultDi;
Métodos
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
.
Interface Phalcon\Di\DiInterface
Código fuente en GitHub
Namespace |
Phalcon\Di |
|
Uses |
ArrayAccess |
|
Extends |
ArrayAccess |
Interface for Phalcon\Di\Di
Métodos
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
Class Phalcon\Di\Exception
Código fuente en GitHub
Namespace |
Phalcon\Di |
|
Extends |
\Exception |
Las excepciones lanzadas en Phalcon\Di usarán esta clase
Class Phalcon\Di\Exception\ServiceResolutionException
Código fuente en GitHub
Namespace |
Phalcon\Di\Exception |
|
Extends |
\Phalcon\Di\Exception |
Phalcon\Di\Exception\ServiceResolutionException
Class Phalcon\Di\FactoryDefault
Código fuente en GitHub
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
Métodos
public function __construct();
Constructor Phalcon\Di\FactoryDefault
Class Phalcon\Di\FactoryDefault\Cli
Código fuente en GitHub
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
Métodos
public function __construct();
Constructor Phalcon\Di\FactoryDefault\Cli
Interface Phalcon\Di\InitializationAwareInterface
Código fuente en GitHub
Interface for components that have initialize()
Métodos
public function initialize(): void;
Abstract Class Phalcon\Di\Injectable
Código fuente en GitHub
Namespace |
Phalcon\Di |
|
Uses |
stdClass, Phalcon\Di\Di, Phalcon\Session\BagInterface |
|
Extends |
stdClass |
|
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
Propiedades
/**
* Dependency Injector
*
* @var DiInterface|null
*/
protected container;
Métodos
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
Interface Phalcon\Di\InjectionAwareInterface
Código fuente en GitHub
This interface must be implemented in those classes that uses internally the Phalcon\Di\Di that creates them
Métodos
public function getDI(): DiInterface;
Devuelve el inyector de dependencias interno
public function setDI( DiInterface $container ): void;
Configura el inyector de dependencia
Class Phalcon\Di\Service
Código fuente en GitHub
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();
Propiedades
/**
* @var mixed
*/
protected definition;
/**
* @var bool
*/
protected resolved = false;
/**
* @var bool
*/
protected shared = false;
/**
* @var mixed|null
*/
protected sharedInstance;
Métodos
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
Class Phalcon\Di\Service\Builder
Código fuente en GitHub
Namespace |
Phalcon\Di\Service |
|
Uses |
Phalcon\Di\DiInterface, Phalcon\Di\Exception |
Phalcon\Di\Service\Builder
Esta clase construye instancias según definiciones complejas
Métodos
public function build( DiInterface $container, array $definition, mixed $parameters = null );
Construye un servicio usando una definición de servicio compleja
Interface Phalcon\Di\ServiceInterface
Código fuente en GitHub
Representa un servicio en el contenedor de servicios
Métodos
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
Interface Phalcon\Di\ServiceProviderInterface
Código fuente en GitHub
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 () {
// ...
}
);
}
}
Métodos
public function register( DiInterface $di ): void;
Registra un proveedor de servicios.