我有许多辅助函数-Grouped In Classes - 用于(格式化字符串和日期,URL助手)我想要使用并在几个包中共享,我需要知道关于我可以将这些帮助函数放在哪里的最佳实践捆绑包之间共享。
我想到的是创建一个帮助程序包,并在我项目中的另一个包中使用此包,或者使用供应商帮助程序。
那么我如何才能做到这一点以及创建共享助手以便在多个捆绑包中使用的最佳做法。
如果有任何参考我可以看一下,请与我分享。
提前谢谢。
答案 0 :(得分:1)
如果你有通用类,它应该被分组在一个包中(如你所说的“Helper bundle”),如果你的情况可以,则应该将类定义为服务。
如果您在多个项目中使用此捆绑包并且希望将来升级它,您应该考虑将此捆绑包移动到单独的仓库并将其定义为“独立”捆绑包(因此您可以将其包括在内)作曲家和供应商目录下的项目。
答案 1 :(得分:1)
最佳做法是创建一个包含这些类的PHP库。如果你真的需要Symfony集成(例如DIC配置),那么创建依赖于这个库的bundle。
每个使用你的bundle的bundle都必须在它的composer.json中依赖它。因此,每次安装依赖于它的bundle时,它都会被自动安装。
答案 2 :(得分:1)
有很多很好的库存例子,可以使用作曲家导入并使用,即使它们本身不是捆绑包,例如,请查看Doctrine\Common。
无论如何,您也可以像创建Symfony中的任何其他捆绑包一样创建捆绑包,并根据需要构建代码。您会注意到许多Doctrine的捆绑包将使用共享库Doctrine\Common
。
答案 3 :(得分:1)
我认为最佳实践是创建帮助程序包并在帮助程序包中创建service 然后你可以在几个包中使用服务。
虚拟示例:在您的服务Helper.php
namespace HelperBundle\Services;
class Helper{
protected $url;
public function __construct(){
}
}
在Dependency Injection文件夹中的ProfileTreeUserExtension.php
确认加载的服务配置文件是sevices.yml
namespace HelperBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class ProfileTreeLayoutExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
}
}
service.yml
中的
services:
helper.service:
class: HelperBundle\Services\Helper
然后您可以在多个捆绑包中调用HelperService
$helper = $this->container->get('helper.service');
您还可以在其他服务中扩展Helper类
use HelperBundle\Services\Helper;
class AnotherService extends Helper{}
的好文章