Samiron
Samiron

Reputation: 5317

symfony2: accessing REST api from command

I have a symfony2 based application that basically exposes REST APIs. The application does not have any UI.

In the same application there are some commands that are created to manipulate the resources. Like creating a user, reseting password of a user, delete a user, assigning a user to particular group etc.

Now I want the command classes to use the REST APIs (they are nothing but controller actions) to perform the actual operations because those REST APIs are already equipped with validation logics or required other business logics etc.

Question: What is the best option to use the REST APIs (aka the controller actions) from Command classes? I can think of following two approaches.

  1. Creating Request object inside command class. Setting proper request content, header etc. Include the controller class and call the controller action statically with the created request object.

  2. Use curl to make the http calls with proper content and headers.

Among these two approaches above, the first one seems saner to me however it feels like there should be more elegant way to achieve this. Any suggestion?

Upvotes: 0

Views: 302

Answers (1)

Cerad
Cerad

Reputation: 48865

The curl approach allows you to completely disconnect your api app from your commands. You could even have your command on a development server hit your production app. It's actually quite a clean approach and indirectly helps to test your api's. By the way, if you do end up with the curl approach then a 3rd party library such as guzzle can make life much easier.

Calling the controller actions directly can be awkward. As you pointed out, you will need to fake a request object, populate it (one assumes) from command line arguments, instantiate a controller, call the action and get a response and then unpack the response to see what happened. Just a lots of "stuff" to do. And of course it "couples" your command code quite strongly with the controller framework code.

What I like to do is to move the actual "business" code to their own services and then inject the services into the controllers. The controller action then become very thin. The action unpacks arguments from the request, calls the services and then packs the results into a response.

Likewise, the services are also injected into the command objects. The command then unpacks it's arguments, calls the services then does whatever with the results.

To me at least this results in a cleaner design. The services are easier to test and of course it's easy to share functionality between controllers and commands.

Of course you may already have a bunch of code inside your controller actions and mass refactoring is just not practical. In that case, go with the fake request route.

Upvotes: 1

Related Questions