问题
What is the best way to put custom library or helper methods in symfony? I am using doctrine with my project. One place I consider to put is under
project_root/lib/vendor/MyClasses/But if I want to create a class or helper function which will use some core symfony/doctrine methods and return a result then how to do that and where should I put it? I want it to call from different modules to avoid code duplication.
回答1:
As for the custom library part of the question, you might probably want to put your external library into the lib/vendor folder. Since symfony doesn't automatically load everything that's in there, you'll have to tell its autoloader to do so.
You can either extend your config/ProjectConfiguration.class.php (as described here) or (and this is the much simpler and cleaner way) you add them to your config/autoload.yml (you might have to create this one). For the latter option, this is a great place to start looking at.
回答2:
It seems to be a duplicate question.
As asked in symfony's 1.2 "Definitive Guide" docs :
Helper functions (regular PHP functions returning HTML code) should be saved in a file called FooBarHelper.php, where FooBar is the name of the helper group. Store the file in the apps/myapp/lib/helper/ directory (or in any helper/ directory created under one of the lib/ folders of your project) so it can be found automatically by the use_helper('FooBar') helper for inclusion.
So, if you want to create custom helper FooBar for foo() function, create file lib/helper/FooBarHelper.php :
function foo() {echo "foo!"; }
to use it in your template:
use_helper('FooBar')
....
foo(); //outs "foo!"
来源:https://stackoverflow.com/questions/5212649/how-to-create-use-custom-classes-and-helper-in-symfony-1-4