首页 > Symfony 2 如何扩展第三方方案

Symfony 2 如何扩展第三方方案

在symfony2 的目录结构里面 该如何扩展第三方呢?
自己在 vendor 里面写 还是有规定目录格式?
symfony1 里面提供了helper 的模式,2里面是否也有相同的机制?


我直接从文档里粘来一些代码:

扩展某个bundle,只需要在你自己bundle里,通过getParent()方法,声明被扩展的bundle是哪个,下面就是以FOSUserBundle作为扩展对象。

// src/Acme/UserBundle/AcmeUserBundle.php
namespace Acme\UserBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class AcmeUserBundle extends Bundle
{
    public function getParent()
    {
        return 'FOSUserBundle';
    }
}

扩展某个Controller更加简单,直接继承目标Controller就好了:

// src/Acme/UserBundle/Controller/RegistrationController.php
namespace Acme\UserBundle\Controller;

use FOS\UserBundle\Controller\RegistrationController as BaseController;

class RegistrationController extends BaseController
{
    public function registerAction()
    {
        $response = parent::registerAction();

        // ... do custom stuff
        return $response;
    }
}

至于其他的如模板、路由等,你要复用、重写哪一个,就在你自己的bundle里,以相同文件路径创建就好了。

文档:http://symfony.com/doc/current/cookbo...

UPDATE1:

如果你只是想要加第三方的代码进去,按规范是应该放vendors里,如果你的代码符合PSR-0,那就可以实现自动的加载;如果不符合,你要在app/autoload.php里加相应的include。

至于是否能够全局使用扩展后的代码,取决于调用,不取决于定义。为了维护的方便,你可以自己抽象interface,或者定义sf2里的service。

你可以参考下sf2的bundle的文档,以及Composer。

【热门文章】
【热门文章】