我正在学习Auraphp,我想编写示例代码。假设我有以下文件:
public/index.php:
use Aura\Di\ContainerBuilder;
use MyPackage\Component\Authentication\AuthenticateFlow;
require_once dirname(__DIR__) . '/vendor/autoload.php';
$builder = new ContainerBuilder();
$di = $builder->newInstance();
$di->set('authenticateFlow', $di->lazyNew(AuthenticateFlow::class));
$authenticateFlow = $di->get('authenticateFlow');
$authenticateFlow->showName('Belkin');/src/Components/Authentication/AuthenticationFlow.php:
namespace MyPackage\Components\Authentication;
class AuthenticationFlow
{
public function showName($name)
{
echo $name;
}
}这很好用。现在假设我有另一个类(/src/Components/Authentication/Filter.php),它有一个名为filterInput的方法:
namespace MyPackage\Components\Authentication;
class Filter
{
public function filterInput($input)
{
return htmlspecialchars($input);
}
}如何向AuthenticationFlow注入过滤器,以使用filterInput()方法?我希望在AuthenticationFlow::showName()中有这样的内容:
echo $this->filter->filterInput($name);我知道我需要在AuthenticationFlow构造函数中注入Filter类,但是我不知道是否可以使用在index.php中构建的容器。如果我需要在AuthenticationFlow中创建另一个容器,index.php将如何意识到它?
发布于 2019-12-12 06:19:15
您的应用程序需要大量使用di容器,以便注入必要的依赖项。这不是奥拉的情况。
让我们后退一步,看看如果你不使用容器,你会怎么做。
为了在Filter中使用AuthenticationFlow对象,您需要通过构造函数或setter方法注入Filter对象。在下面的示例中,我使用构造函数注入。
class AuthenticationFlow
{
protected $filter;
public function __construct(Filter $filter)
{
$this->filter = $filter;
}
public function showName($name)
{
return $this->filter->filterInput($name);
}
}因此,您将创建一个AuthenticationFlow对象,如下所示。
$auth = new AuthenticationFlow(new Filter);在Aura.Di的例子中,您可能会做如下的事情
$object = $di->newInstance(AuthenticateFlow::class);如果自动解析关闭,则需要定义依赖项如下所示
$di->params[AuthenticateFlow::class]['filter'] = $di->lazyNew(Filter::class);在应用程序中,这是不正确的。您可能需要在不同的AuthenticateFlow上安装HelloController::class。
Class HelloController
{
protected $auth;
public function __construct(AuthenticationFlow $auth)
{
$this->auth = $auth;
}
public function execute()
{
// Do something
}
}因此,在这种情况下,需要通过di本身实例化HelloController::class。否则,依赖项将不会自动注入。
$object = $di->newInstance(HelloController::class);您可以在多个类中扩展Aura\Di\ContainerConfig和定义服务。
例子:
namespace YourVendor;
use Aura\Di\Container;
use Aura\Di\ContainerConfig;
class Config extends ContainerConfig
{
public function define(Container $di)
{
$di->set(HelloController::class, $di->lazyNew(HelloController::class));
$di->params[HelloController::class]['auth'] = $di->lazyNew(AuthenticateFlow::class);
$di->params[AuthenticateFlow::class]['filter'] = $di->lazyNew(Filter::class);
}
public function modify(Container $di)
{
// You can get the service and modify if needed
// $auth = $di->get('authenticateFlow');
}
}现在你的index.php看起来
require_once dirname(__DIR__) . '/vendor/autoload.php';
$builder = new ContainerBuilder();
$di = $container_builder->newConfiguredInstance([
'YourVendor\Config',
]);
$hello = $di->newInstance(HelloController::class);
$hello->execute();正如我在上一个答复中提到的,我建议您先检查文档。从长远来看,这真的会对你有帮助。
https://stackoverflow.com/questions/59278782
复制相似问题