在Symfony2中包含用户自定义函数的最佳实践

[英]Include User Custom Functions Best Practice in Symfony2


I am a newbie in Symfony2 and I can't understand where I should make includes with my custom cross-projects functions (e.g. array_merge_overwrite, array_last, etc.)? I use both types of apps: web (MVC) and console (extends ContainerAwareCommand).

我是Symfony2的新手,我不明白应该在哪里使用我的自定义跨项目函数(例如array_merge_overwrite、array_last等)进行include ?我使用两种类型的应用程序:web (MVC)和控制台(扩展ContainerAwareCommand)。

Or there is another "right way" for this?

或者有另一种“正确的方法”?

2 个解决方案

#1


7  

Create a service and put your common functionality in it. For example, you can name it ArrayService and register it in the container as array.service. You can then access this service from controllers via

创建一个服务并将您的公共功能放在其中。例如,您可以将其命名为ArrayService,并将其注册到容器中作为array.service。然后您可以通过控制器访问此服务。

$this->get('array.service');

and from commands via

从命令通过

$this->getContainer()->get('array.service');

So, your code will look something like this:

你的代码会是这样的:

$element = $this->get('array.service')->last($array); // or ->arrayLast($array)

If you need the same functionality across several projects, make a bundle with that service and add it to the deps file of each project. Then it will be installed when you run the bin/vendors install script.

如果您需要跨多个项目使用相同的功能,请使用该服务创建一个包,并将其添加到每个项目的deps文件中。然后,当您运行bin/vendor安装脚本时,它将被安装。

#2


0  

You can convert your functions to static methods of some class to make them autoloadable. Or... well... Place them where you want and require() from where you need them every time.

您可以将您的函数转换为某个类的静态方法,以使它们具有自动可读性。还是……嗯…将它们放在您想要的地方,并在每次需要它们的地方放置()。

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2011/11/15/cd83c5c1aa20dcf548dcdc0daf3f6791.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告