Bra*_*dys 5 php symfony solarium
我使用 Symfony 5 和 Solarium。我想在我的控制器(从 AbstractController 扩展)中获取项目目录(或根目录)。
我看到了一些关于内核、创建新服务等的答案。
但是,它不只是一个调用项目目录而不创建一些自定义服务等的函数吗?
谢谢 !
tol*_*gol 11
您不需要任何服务。您可以从控制器中的容器中获取。
$this->getParameter('kernel.project_dir');
另一种方法是将它绑定在 yaml 上。
_defaults:
bind:
# pass this value to any $projectDir argument for any service
# that's created in this file (including controller arguments)
string $projectDir: '%kernel.project_dir%'
Run Code Online (Sandbox Code Playgroud)
因此,您可以将每个服务和控制器注入为$projectDir。
public class YourController {
public function index(string $projectDir){
// Your code
}
}
Run Code Online (Sandbox Code Playgroud)
public class YourService {
public function __construct(string $projectDir){
// Your code
}
}
Run Code Online (Sandbox Code Playgroud)
https://symfony.com/doc/current/configuration.html#accessing-configuration-parameters
从 Symfony 6.1 开始,您可以自动装配参数
https://symfony.com/blog/new-in-symfony-6-1-service-autowiring-attributes
<?php
use Symfony\Component\DependencyInjection\Attribute\Autowire;
class MyService
{
public function __construct(
#[Autowire('%kernel.project_dir%/config/dir')]
private $dir,
) {}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3954 次 |
| 最近记录: |