[英]Preserving auto-completion abilities with Symfony2 Dependency Injection
我正在使用PHP Storm作為我的IDE,但我相信其他IDE如Netbeans將會遇到與我將在下面解釋的相同的問題。
當使用像Symfony2這樣的框架時,我們添加了依賴注入的精彩世界。 因此,可以使用類似以下代碼段的代碼簡單地實例化對象:
$myThingy = $this->get('some_cool_service');
這非常方便,因為事先已經配置了對象。 一個問題是,自動完成基本上完全在任何PHP IDE中斷,因為IDE不知道get()方法返回什么類型。
有沒有辦法保留自動完成? 創建例如Controller的擴展會是答案嗎? 例如:
class MyController extends Controller {
/**
* @return \MyNamespace\CoolService
*/
public getSomeCoolService() {
return new CoolService();
}
}
然后對於應用程序控制器,將MyController指定為基類而不是Controller?
使用Factory類或任何其他可能的方法怎么樣?
它涉及更多,但您仍然可以使用eclipse PDT執行此操作:
$myThingy = $this->get('some_cool_service');
/* @var $myThingy \MyNamespace\CoolService */
更新 : 此頁面上的示例顯示您也可以使用與phpStorm相反的方式:
$myThingy = $this->get('some_cool_service');
/* @var \MyNamespace\CoolService $myThingy */
您可以在控制器中定義私有屬性
class MyController extends Controller
{
/**
* @var \Namespace\To\SomeCoolService;
*/
private $my_service;
public function myAction()
{
$this->my_service = $this->get('some_cool_service');
/**
* enjoy your autocompletion :)
*/
}
}
我使用base Controller類作為bundle。 您需要在方法中注釋返回。 至少這適用於Eclipse。
/**
* Gets SomeCoolService
*
* @return \Namespace\To\SomeCoolService
*/
protected function getSomeCoolService()
{
return $this->get('some_cool_service');
}
我不喜歡/ * var ... * /,因為它對代碼的影響太大了。 我不喜歡私有屬性,因為你可能錯誤地認為服務已經加載。
我使用Komodo Studio,並使用@var標記變量,甚至在方法內部,為我保留自動完成。
namespace MyProject\MyBundle\Controller;
use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\HttpFoundation\Request;
class WelcomeController extends ContainerAware
{
public function indexAction()
{
/*@var Request*/$request = $this->container->get('request');
$request->[autocomplete hint list appears here]
}
}
使用netbeans IDE 7.1.2 PHP
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.