简体   繁体   English

Symfony2 Web服务

[英]Symfony2 Web Service

I'm currently designing a new web application based on Symfony Framework that will serve both web and mobile accesses. 我目前正在基于Symfony Framework设计一个新的Web应用程序,该应用程序将同时为Web和移动访问提供服务。 For illustration purposes I will use the default AcmeDemoBundle from Symfony`s framework to elaborate my question. 出于说明目的,我将使用Symfony框架的默认AcmeDemoBundle来阐述我的问题。

So, DemoBundle gives me the following route: 因此,DemoBundle为我提供了以下路线:

/hello/{name}

So far so good. 到现在为止还挺好。 Now, I want to implement an API in this project that will serve mobile apps, so the route for the same controller as the route above whould be, for instance: 现在,我想在该项目中实现一个将为移动应用程序提供服务的API,因此,与上面的路由相同的控制器的路由应为:

/api/v1/hello/{name}

My doubt is: what's the best way of doing that without replicating code? 我的疑问是:不复制代码的最佳方法是什么? I intend to use the FOSRestBundle for the API and I know that he handles rendering HTML views to, but I'd like to separate the API routes from the web as I put before. 我打算将FOSRestBundle用于API,并且我知道他可以处理HTML视图,但是我想像以前一样将API路由与网络分开。 Maybe should I create a new bundle for the API? 也许我应该为该API创建一个新的捆绑软件?

Create a bundle for the API is not a good practice for the simple reason that you can't easily re-use the bundle in an other project. 为API创建捆绑包不是一个好习惯,原因很简单,因为您不容易在其他项目中重用该捆绑包。

For example, you create PostBundle and his API bundle, APIPostBundle for your A project. 例如,您为A项目创建PostBundle及其API捆绑包APIPostBundle。 If you want to use that bundle for a B project, you need PostBundle and APIPostBundle. 如果要将该捆绑包用于B项目,则需要PostBundle和APIPostBundle。 You created dependency between two bundles and it's a bad practice (Component-Based Development). 您在两个捆绑软件之间创建了依赖关系,这是一个不好的做法(基于组件的开发)。

So, you have to generate an independency bundle with a strength architecture who can allow you less modification if you have to. 因此,您必须生成具有强度架构的独立捆绑包,如果需要的话,该捆绑包可以允许您进行更少的修改。 Use a service for the logical instructions. 将服务用于逻辑指令。 Then, the controller/APIController can manage the route and will call the service methods. 然后, controller/APIController可以管理路由并调用服务方法。 By that way, you can just modify the service without editing the controllers. 这样,您无需修改​​控制器就可以修改服务。

So, your architecture looks like that: 因此,您的架构如下所示:

PostBundle
  Controller
    - PostController
    - APIPostController 
  Service
    - PostService
    - PostServiceInterface

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM