2012-12-21 15 views
6

我是Symfony2的新手,我遇到了一些簡單的問題,但我不確定如何管理它。我需要使用一個簡單的第三方類,我不知道在哪裏以及如何將它存儲在項目結構中。我應該存儲在我的軟件包中的服務,或者我應該將其存儲在供應商目錄中?如果我將它存儲在供應商中,那麼在那裏存儲那些不受Symfony支持的供應商的庫是不是一種不好的做法?在Symfony2中存儲簡單第三方類的位置?

回答

4

通常你會在你的項目中加入Composer。我建議你看看packagist看看你的課堂是否有一個Composer軟件包,否則你不能要求它與作曲家合作。

作曲家將你的課程放在vendor目錄中,你應該把所有'供應商'(第三方庫)放在那裏。看看把它們放在那個目錄中的位置,這樣Composer自動加載器可以自動加載它。

之後,建議爲該特定類創建一個包。在那裏創建服務是最佳做法。舉例來說,如果你的類是Foo您創建加載Foo服務Acme\FooBundle

// src/Acme/FooBundle/DependencyInjection/AcmeFooExtension.php 
<?php 

namespace Acme\FooBundle\DependencyInjection; 

use Symfony\Component\Config\FileLocator; 
use Symfony\Component\DependencyInjection\ContainerBuilder; 
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; 
use Symfony\Component\HttpKernel\DependencyInjection\Extension; 

class AcmeFooExtension extends Extension 
{ 
    /** 
    * this method loads the Service Container services. 
    */ 
    public function load(array $configs, ContainerBuilder $container) 
    { 
     $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); 

     // load the src/Acme/FooBundle/Resources/config/services.xml file 
     $loader->load('services.xml'); 
    } 
<!-- src/Acme/FooBundle/Resources/config/services.xml --> 
<?xml version="1.0" encoding="UTF-8" ?> 

<container xmlns="http://symfony.com/schema/dic/services" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> 

    <services> 
     <!-- Loads the \Foo class as a acme_foo.foo service --> 
     <service id="acme_foo.foo" 
      class="\Foo" 
     ></service> 
    </services> 

</container> 
1

Symfony本身在供應商文件夾中存儲第三方庫。是good practice也可以讓你的第三方課程

如果你不知道該怎麼做,可能this question會有所幫助。

1

我相信使用服務容器將是一個很好的做法。無論如何,服務容器是爲了存儲第三方的depinases並保存鬆耦合而設計的。

看看docs,寫了如何和爲什麼服務容器應該使用。

祝你好運。