Where Do I Create External API functions or Classes? Proper MVC Structure for Web Frameworks - laravel

I am looking to add multiple API's to my senior project on an MVC based framework (Laravel). I understand the basic concept of MVC, but want to make sure that I am doing things according to best practice.
Basically, I am going to have a class/function that takes a query and calls that query on a Amazon's Product API. I have seen an example of calling API's from directly within the Controller on Laravel (see http://www.phplab.info/categories/laravel/consume-external-api-from-laravel-5-using-guzzle-http-client).
Perhaps I don't understand MVC well enough. Should an external API call be in it's own class? And if so, should it be a Controller Class or a Model Class? I hope the Stack Overflow gurus can enlighten me. Let me know if I need to clarify anything!

It depends to what you want to process with external API.
If it's a part of the business, it can be in Model (lot of people put
the business inside the model to follow the encapsulation principle
of OOP).
If it's the explicit process, it should be in Controller
(like most people do).
For example, if you have a model Transaction in bank transfer (that automatically convert the currency, it needs the external API to get the exchange rate), the external API call should be wrapped in model. So controller cannot modify the Transaction object and it will be safe.
In another hand, you can call to external API in controller, do some extra stuffs then set it back to Transaction object. It's also good because model always contains only properties. It makes application also clear enough.
They are 2 ways of use, none is absolutely right or wrong. But if you choose one, follow it, don't mix.
Another, both 2 are only ok. The better way is putting the external calls to other places (modules etc), then call it by single line in model or controller.

Related

Laravel Web and API controller structure. Separate vs DRY

I want to build a Laravel application which users both web and API parts. The common (and mine as well) question is whether to use separate controllers or not.
There are 2 options:
Separate controllers
Laravel API controller structure?
Use one controller and check the request type (is Ajax, or depending on the request link) and return either JSON or HTML.
Laravel resource controllers for both API and non-API use
Those who have the 1-st opinion doesn't explain the DRY problem solution - web and API controllers would be the same except the return statement (JSON or HTML view). But since most post recommend to separate controllers I suspect I don't understand something about the DRY problem solution.
I don't see any disadvantage of the second method. But people say something like
If you use only one controller, you will end up soon with a messy class with thousands of lines. Not only this is not going to scale well, but it will be hard to work with for you and your teammates.
Please explain me the DRY problem solution for the first approach (separate controllers) and the possible underwater rocks in the second approach (single controller)
Please explain which approach is preferable.
I think this is a great question, and I too am keen to see the responses.
I can see the arguments for both approaches. I however would create and maintain separate controllers, whilst using services to share common logic between the controllers where it is known that this will never change.
For example, if you allow users to upload avatar images. I would put such logic in a service and consume this service in both controllers.
The reason for this approach in my mind, is that the web and API logic may diverge and it would therefore be easier to iterate each without impacting the other.
If this is unlikely, then I would still create separate routes, but point them both at the same controllers, so that if it did change in the future, you can simply re-point the API routes to their own controllers.

Layered architecture mvc

I'm creating a web app using an MVC framework. I thought of adding a layer between the controller and the domain models, I think it's called application layer in DDD, to avoid putting logic that is specific to a certain use case in the domain models.
The controller will only interact with this layer and this layer will orchestrate the operation using the domain models. This layer will be kept as thin as possible pushing all the logic that is not use case specific to the domain model.
I will call the classes that belong to this layer DomainCtrl.
Example login scenario:
Model: LoginForm
DomainCtrl: AuthCtrl
UI: ui controller
1.ui controller receives request
2.creates instance of AuthCtrl
3.AuthCtrl creates instance of a LoginForm and fill it with request data passed to authCtrl
4.LoginForm performs the login
5.authCtrl does other things that are specific to this specific way of login -> returns errors to ui controller
Is this a good way to organize an app?
Your question
Is this a good way to structure an app
is a very loaded question. The simple answer is Yes, but the more correct answer is It depends.
Let's start with the simple answer. Having your main application be unaware of the UI is generally a good idea. It means that you can easily consume your application from various places. In DDD this outer layer is usually called Application Layer. It is mainly responsible for orchestrating interactions between your domain, persistence and other resources that you might rely on. This also allows you to have your domain at the center unaware of everything else. This makes your domain easily testable and maintainable if implemented well.
Now the "it depends" part of the answer. DDD is not the only successful way to build an application, and in some cases it might be more of a hinderance than anything else. You have to ask yourself what is my app doing. Are there many domain specific rules? Am I only fetching and storing basic data etc? These are all questions you need to answer before you choose an architecture and technologies.
I would still say you probably won't go wrong by choosing the DDD approach as it is generally a good way to do things.
*Note: Your example is not that clear to me but you should be careful of spilling UI concepts into your domain/application. A login form is completely a UI concept as is auth to a certain extent. You can probably have your application return the details of your user, but the UI layer should decide if the user is allowed to proceed or not.
At a high level view, Yes
But it ultimately depends on "how" you logically separate your layers. In your scenario, I don't see any application layer.
I assume AuthCtrl is the domain? Who creates AuthCtrl? what layer does it exists?

SPring MVC - Several Controllers

I am developing for learning purposes my very first "big" Spring MVC project. I am learning everything by myself (and of course, thanks to this amazing community).
What I am starting to wonder is... Is my design "correct/valid"? So far I am creating one Controller per View/Page specially because of the ModelAttributes (attached to the method).
Is that fine? Should I start doing it in some other way? Are there "offical" patterns in this matter?
To start, I assume you are creating a web project based on your use of ModelAttribute. You want to follow the MVC (Model, View, Controller) convention. The "Model" is the data you are manipulating. This data should be retrieved via a service layer. Then, your controller should call your service methods to get the data, making your controllers completely agnostic of your data. This is nice because you are free to change your data structure, e.g. migrating from MySQL to MongoDB, without worrying about changing your controller, all you need to change is your service layer. Also, this allows for controllers to use many different services in certain instances. Your controller receives requests from the client, e.g. the website user's page requests, GET/POST requests, etc., and performs some action, usually fetching/updating data via the service layer, and then returns a view. Each controller can take many requests, and can render many views. It is good practice to break up controllers by function. For example, if you had two different sections for your website, one for Admins, and one for Guests, then you may want to use one controller to process the Admin requests, and another to process the Guest requests. Each of these controllers can handle all requests from Admins/Guests accordingly. You may be a bit confused about controllers. Each method in a controller is bound to a single request/view, but a controller may have many such methods.
As you are learning, I would suggest exploring some client-side mvc frameworks like AngularJS. Angular allows very easy data binding and manipulation options, and makes it pretty easy to create RESTful web services.

Naming conventions for service wrapper cfc's in Coldfusion MVC

I have an application that handles licence registrations for various product. I'm currently re-factoring into a basic MVC framework (not using any of the big ones yet). We have various basic scenario's e.g. someone can make a cc purchase of a product via the website. This fires the create customer, create order, create licence etc objects (basically just db inserts using beans and gateways as I think that is the "standard"?).
Anyway, to handle all this I'm calling a purchaseService.cfc, which validates the various business rules and wraps the persistence(db) layer processes together. That seems to work fine and I thought having a purchaseService cfc contained that process well.
Now we need another, similar process where a key can be "registered" to achieve the same as above. i.e. provide a licence to the customer. (obviously there will be differing rules).
As far as naming conventions go, are there any rules to help decide what to call these service "wrapper" type cfc's. Most of the examples I see are per object, e.g. the user object has a userGateway and userService and don't give examples of cases where we need a wrapper to call multiple objects. Is what I've done ok convention wise using a purchaseService object? (I was going to call it CustomerlicenceOrder.cfc based on the other objects it was dependent on. What will I do with the new requirement? Perhaps create another service object? Called PurchaseByKeyService? Doesn't sound right to me. I have read so much on OO and MVC etc etc but the more I read the more questions I have :)
Thanks
There's certainly nothing wrong with grouping actions into a common service. In fact, it's usually more accepted than just creating standalone services for each domain object.
Read more on the Service Layer pattern if you're interested.

Coldfusion, whats the advantage of front controller design over page controller?

I'm from a non-computing background and I'm struggling to getting my head around MVC design approaches and frameworks in general. I "get" code re-use, and separation of logic from display, and I "get" encapsulation and decoupling, but I don't get this.
At the moment I simply put everything in root, a separate subfolders for images, cfcs, and _includes, all database interaction via cfcs. I do all my processing at the top of the page, then a comment line then display/page layout below that.
Most of the frameworks I have looked at seem to favour a front controller, so my simplistic version of a top controller MVC design would be a subfolder for cfcs, controllers, and views and a big switch statement in index.cfm
<cfif not IsDefined("URL.event")>
<cflocation url="index.cfm?event=home" addtoken="No">
</cfif>
<cfswitch expression="#url.event#">
<cfcase value="home">
<cfinclude template="controllers/home.cfm"/>
<cfinclude template="views/home.cfm"/>
</cfcase>
<cfcase value="about">
<cfinclude template="controllers/about.cfm"/>
<cfinclude template="views/about.cfm"/>
</cfcase>
</cfswitch>
.. but what real advantage does that give me over a page controller design? Unless it's just the kind of sites I write, I always seem to find that the controller logic is specific to a view, its not like one controller could fit several views or several controllers could output to one view, so what would be the point of separating them?
The light hasn't come on for me yet, any pointers?
By "top" controller, I think you mean "front" controller, a single point of entry for requests into an application. As #bpanulla wrote, most ColdFusion frameworks use this design pattern. This becomes particularly interesting with URL rewriting, where it becomes easy to have search engine safe URLs by intercepting the a URL (e.g. domain.ext/i/am/friendly.ext) and routing it to some standard file such as index.cfm while making the requested URL a parameter (often as a request header). This also makes site redesigns where URLs change easier because it lends itself well to aliasing or redirects.
As far as controllers are concerned, they are usually tightly coupled to a particular URL or URL pattern. It's possible be more loosely coupled with controllers, but in practice I find that's an emergent property after multiple refactorings. What should be underlying the controller is one or more calls to a service layer that talks to the database, executes business process, creates stateful entities, etc... Then the controller receives the service layer's outputs and places them into whatever mechanism (e.g. an event object) is used to pass data to the view(s).
It's the service layer that's meant to be reusuable not the controllers. The controllers are merely an extension of whatever framework an application works within. The idea being that you should be able to switch frameworks with very little impact to the views and service layer. The piece that needs to be touched are the controllers.
So a given service object in a service layer should be able to service multiple controllers. For example, consider showing a logged in users' information as a widget on a site. There might be different pages served by different controllers, but each would call the same service object to get logged in user data that presumably might be given to the same view that renders the widget.
Update: Front Controller Advantages
Security: centralized authentication and authorization.
i18n & l10n: inject the right language pack into the request globally
Process Orchestration: think multi step checkout process for a shopping cart where you don't want the back and forward buttons to work - by routing everything through the front controller you're able to enforce what step (i.e. the state)
Logging & Tracking: easily add Google Analytics or other request tracking to a site by making the addition in just one place
Error Handling: centralized behavior
Now many of these items can also be done using <cferror> and Appplication.cfc, but I find it easier to have one centralized point.
Useful Links
http://java.sun.com/blueprints/corej2eepatterns/Patterns/FrontController.html
http://msdn.microsoft.com/en-us/library/ff648617.aspx
You actually implemented the crux of Fusebox (http://www.fusebox.org/) with what you wrote. There's nothing wrong with that, and most of the ColdFusion community used something similar to that for many years - Fusebox was the most-used CF framework (in my experience) until just a few years ago when ModelGlue, Mach-II and the other second generation CF frameworks came about.
One thing I can point out is that your approach to controllers (as .cfm files) actually does not enforce encapsulation in the typical OOD fashion, with specific arguments going to an object method call. Unless you are extremely dilligent, over time your .cfm controllers may wind up accumulated a large number of undocumented parameters that alter behavior to solve one problem or another.
With the various frameworks you also get nice features like Application, Session, and Request specific code (onApplicationStart, onRequestEnd, etc). But you can always get those through a simple Application.cfc.

Resources