dongyuan1870 2014-06-02 13:18
浏览 22
已采纳

Symfony2可重用的代码段功能

I am using Symfony2 lately and I keep wondering when I should create a service and when I should create a class.

For example I do have this little snippet function that is a very reusable piece of code. So because of that I do not want that piece of code in my controller. Meaning that I would want to use it anywhere in my bundle.

It's very simple, but it basically generates a full url for me based on a slug/path. Now please note that this could be anything else for example a customStringGenerator() or what so ever.

The snippet:

public function generateUrlFromPath(Request $request, $path)
{
    return $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath() . $path;
}

Now I could make some sort of Toolkit or UrlHelper class and define it as a service so I can easily inject the Request object, but it seems overdone for me to create a service for such a simple method.

What would anyone suggest in this case? What would you guys do when you have created reusable functions?

Thanks for your help so far.

  • 写回答

2条回答 默认 最新

  • dsjk3214 2014-06-02 13:30
    关注

    For reusability, I use:

    • Services (When I need to inject other dependencies through constructor), so you don't have to do it manually everytime.

    • Helper controller, which my controllers extend.

    • Classes with public static functions.

    • Traits (PHP >= 5.4), when you need to share same methods in a few classes, to help overcome single class inheritance limitation.

    For your function up there, I would personally make a protected function inside a Helper controller, but a service would be ok too, even it is such a small piece of code. You might end up writing more code to that service later.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?