這是一個容器感知服務的完整實現示例。
但應注意避免注射整個容器。最好的做法是僅注入所需的組件。有關該主題的更多信息,請參閱Law of Demeter - Wikipedia。
爲此,該命令將幫助你找到所有可用的服務:
# symfony < 3.0
php app/console debug:container
# symfony >= 3.0
php bin/console debug:container
不管怎樣,下面是完整的例子。
的app/config/services.yml
文件:
app.my_service:
class: AppBundle\Service\MyService
calls:
- [setContainer, ['@service_container']]
服務類src/AppBundle/Service/MyService.php
:
<?php
namespace AppBundle\Service;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
class MyService implements ContainerAwareInterface
{
use ContainerAwareTrait;
public function useTheContainer()
{
// do something with the container
$container = $this->container;
}
}
而且finaly控制器在src/AppBundle/Controller/MyController.php
:
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
/**
* My controller.
*/
class MyController extends Controller
{
/**
* @Route("/", name="app_index")
* @Method("GET")
*/
public function indexAction(Request $request)
{
$myService = $this->get('app.my_service');
$myService->useTheContainer();
return new Response();
}
}
這是你滿級或者只是一個子集? $ this->容器不存在於你的類中。請顯示您的「使用」語句 – saamorim
您是否嘗試在您的服務定義中設置調用參數以調用setContainer方法將service_container作爲參數傳遞? – Picoss