- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我需要让 Doctrine 在我的助手中工作,我正在尝试像我通常在 Controller 中那样使用:
$giftRepository = $this->getDoctrine( )->getRepository( 'DonePunctisBundle:Gift' );
但这给了我:
FATAL ERROR: CALL TO UNDEFINED METHOD DONE\PUNCTISBUNDLE\HELPER\UTILITYHELPER::GETDOCTRINE() IN /VAR/WWW/VHOSTS/PUNCTIS.COM/HTTPDOCS/SRC/DONE/PUNCTISBUNDLE/HELPER/UTILITYHELPER.PH
我在这里缺少什么?
编辑:
服务文件
services:
templating.helper.utility:
class: Done\PunctisBundle\Helper\UtilityHelper
arguments: [@service_container]
tags:
- { name: templating.helper, alias: utility }
帮助文件的第一行
<?php
namespace Done\PunctisBundle\Helper;
use Symfony\Component\Templating\Helper\Helper;
use Symfony\Component\Templating\EngineInterface;
class UtilityHelper extends Helper {
/*
* Dependency injection
*/
private $container;
public function __construct( $container )
{
$this->container = $container;
}
最佳答案
这里的问题是您的 Helper 类不是容器感知的;也就是说,它不知道 Symfony 加载的所有服务(monolog、twig、...和 doctrine)。
您通过将“Doctrine ”传递给它来解决这个问题。这称为依赖注入(inject),是使 Symfony 令人敬畏的核心之一。这是它的工作原理:
首先,给你的 Helper 类一个 Doctrine 服务所在的地方,并在 Helper 的构造函数中要求它:
class UtilityHelper
{
private $doctrine;
public function __construct($doctrine)
{
$this->doctrine = $doctrine;
}
public function doSomething()
{
// Do something here
}
}
然后,您使用 services.yml 来定义 Symfony 应该如何构建 Helper 的实例:
services:
helper:
class: Done\PunctisBundle\Helper\UtilityHelper
arguments: [@doctrine]
在这种情况下,@doctrine
是一个占位符,意思是“在这里插入 Doctrine 服务”。
所以现在,在你的 Controller 或任何其他容器感知的东西中,你可以像这样通过 Helper 类访问 Doctrine:
class SomeController()
{
public function someAction()
{
$this->get("helper")->doctrine->getRepository(...);
}
}
编辑
查看您的编辑后,您似乎将整个服务容器注入(inject)了 Helper 类。这不是最佳做法——您应该只注入(inject)您需要的东西。但是,您仍然可以这样做:
服务.yml
services:
helper:
class: Done\PunctisBundle\Helper\UtilityHelper
arguments: [@service_container]
UtilityHelper.php
class UtilityHelper
{
private $container;
public function __construct($container)
{
$this->container = $container;
}
public function doSomething()
{
// This won't work, because UtilityHelper doesn't have a getDoctrine() method:
// $this->getDoctrine()->getRepository(...)
// Instead, think about what you have access to...
$container = $this->container;
// Now, you need to get Doctrine
// This won't work... getDoctrine() is a shortcut method, available only in a Controller
// $container->getDoctrine()->getRepository(...)
$container->get("doctrine")->getRepository(...)
}
}
我在其中包含了一些注释,强调了一些常见的陷阱。希望这会有所帮助。
关于php - 如何让 Doctrine 在 Symfony2 的辅助函数中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15551983/
我是一名优秀的程序员,十分优秀!