Best way of passing response information from Model to Controller using Laravel - laravel

The Model View Controller architecture tells me that all my business logic should be inside the Model, while the data flow should be handled by the Controller.
Knowing this, while I'm dealing with my logic inside the Model, I need to let the Controller know if he's supposed to redirect to another url, redirect back, what kind of message or variable to pass during the redirection, etc.
What is the best way of doing this?
I can think of some ways, like throwing exceptions on the Modeland catching them on the Controller or returning an array from the Model and treating it on the Controller, but none of them seem very nice. The easiest way would be calling the Redirect->to() (or back()) inside the Model and just returning the Model's return on the Controller, but it seem to break the architecture's separation of rules.
Is there a "right" way of doing this? What would be the pros and cons of each way?

EDIT:
The answer below is old. Laravel now includes a bunch of different ways of handling common problems.
For example, use Laravel's FormRequest's as a way of validating data easily on controller methods, and Jobs to handle business logic for creating / updating models.
OLD POST:
This is a common question, and while the 'MVC' pattern is nice for a basic starting point for a web app, I feel like the majority of developers always need another intermediate service for validation, data handling, and other problems that come up during development.
To answer your question without bias: There is no right way.
To answer your question with my own personal bias, I feel the majority of developers will use the Repositories or Services pattern to handle intermediate data handling between the controller and the model, and also have separate classes for validation as well.
In my opinion, Repositories are better for a framework and data agnostic design (due their interface driven implementation), and Services are better for handling the business logic / rules. Controllers are better used for handling responses and for passing the input data to the repository or the service.
The paths for each of these patterns are the same though:
Request -> Controller (Validation) -> Service -> Model -> Database
Request -> Controller (Validation) -> RepositoryInterface -> Model -> Database
Validation is in brackets since input isn't passed from the validator to the service / repository, the input sent to the validator, gives the 'OK', and let's the controller know it's ok to send the data to the Service / Repository to be processed.
I only use Services when I'm absolutely positive I won't be changing frameworks or data sources. Otherwise I'll use Repositories. Repositories are just a little more work to setup, since you'll need to make Laravel resolve the interface to your repository class through its IoC.
Services Example:
The Service:
namespace App\Services;
use App\Models\Post;
class PostService
{
/**
* #var Post
*/
protected $model;
/**
* Constructor.
*
* #param Post $post
*/
public function __construct(Post $post)
{
$this->model = $post;
}
/**
* Creates a new post.
*
* #param array $input
*/
public function create(array $input)
{
// Perform business rules on data
$post = $this->model->create($input);
if($post) return $post;
return false;
}
}
The Controller:
namespace App\Http\Controllers;
use App\Services\PostService;
use App\Validators\PostValidaor;
class PostController extends Controller
{
/**
* #var PostService
*/
protected $postService;
/**
* #var PostValidator
*/
protected $postValidator;
/**
* Constructor.
*
* #param PostService $postService
* #param PostValidator $postValidator
*/
public function __construct(PostService $postService, PostValidator $post Validator)
{
$this->postService = $postService;
$this->postValidator = $postValidator;
}
/**
* Processes creating a new post.
*/
public function store()
{
$input = Input::all();
if($this->postValidator->passes($input)) {
// Validation passed, lets send off the data to the service
$post = $this->postService->create($input);
if($post) {
return 'A post was successfully created!';
} else {
return 'Uh oh, looks like there was an issue creating a post.';
}
} else {
// Validation failed, return the errors
return $this->postValidator->errors();
}
}
}
Now with this pattern, you have a nice separation of all your processes, and a clear indication of what each of them do.
For a repository example, Google 'Laravel Repository Pattern'. There are tons of articles about this.

Actually - in Laravel 5 that is not the best way to do it. Business logic should not be in models. The only thing that models should do is retrieve and store data from your database.
You are better off using the CommandBus or ServiceProviders to handle application logic and business rules. There are many articles on the web about these, but personally I prefer laracasts.com as the best learning resource.

Related

Enabling / Disabling Features in a Laravel App

I'm building a Laravel app, which has a number of various features. I want to be able to enable or disable them depending on a particular domain's requirement. Currently, I have in my config a series of flags such as:
'is_feature_1_enabled' => true,
'is_feature_2_enabled' => false,
... and so on.
Then in my controllers and views, I check those config values to see whether or not I should be displaying something, allowing certain actions, etc. My app is starting to get polluted with these kinds of checks everywhere.
Is there a best practice method of managing features in a Laravel app?
This is technically called feature flags - https://martinfowler.com/articles/feature-toggles.html
depends on your requirements, flags in config/database, rollout, etc...
But it's basically if's in code and cannot be clean.
Laravel packages:
https://github.com/alfred-nutile-inc/laravel-feature-flag
https://github.com/francescomalatesta/laravel-feature
Some services:
https://launchdarkly.com/
https://bullet-train.io/
https://configcat.com/
Also look at https://marketingplatform.google.com/about/optimize/ for frontend.
I've encountered the same problem when I tried to implement multiple hotel providers.
What I did was using service container.
first you will create class for each domain With his features:
like Doman1.php ,Domain2.php
then inside each one of those you will add your logic.
then you gonna use binding in your app service provider to bind the domain with class to use.
$this->app->bind('Domain1',function (){
return new Domain1();
});
$this->app->bind('Domain2',function (){
return new Domain2();
});
Note you can use general class that holds the features goes with all domains then use that general class in your classes
Finally in your controller you can check your domain then to use the class you gonna use
app(url('/'))->methodName();
Look like you are hard coding things based on config values to enable or disable certain features. I recommend you to control things based on named routes rather than config value.
Group all the route as a whole or by feature wise.
Define name for all routes
Control the enable/disable activity by route name and record in database
Use Laravel middleware to check whether a particular feature is enabled or disabled by getting the current route name from request object and matching it with the database..
so you will not have the same conditions repeating every where and bloat your code..
here is a sample code show you how to retrieve all routes, and you can match the route group name to further process to match your situation.
Route::get('routes', function() {
$routeCollection = Route::getRoutes();
echo "<table >";
echo "<tr>";
echo "<td width='10%'><h4>HTTP Method</h4></td>";
echo "<td width='10%'><h4>Route</h4></td>";
echo "<td width='80%'><h4>Corresponding Action</h4></td>";
echo "</tr>";
foreach ($routeCollection as $value) {
echo "<tr>";
echo "<td>" . $value->getMethods()[0] . "</td>";
echo "<td>" . $value->getPath() . "</td>";
echo "<td>" . $value->getName() . "</td>";
echo "</tr>";
}
echo "</table>";
});
and here is a sample middleware handler where you can check whether a particular feature is active by matching with what you have already stored in your database..
public function handle($request, Closure $next)
{
if(Helper::isDisabled($request->route()->getName())){
abort(403,'This feature is disabled.');
}
return $next($request);
}
Assuming that those features are only needed for HTTP requests.
I would create a default Features base class with all the default flags:
Class Features {
// Defaults
protected $feature1_enabled = true;
protected $feature2_enabled = true;
public function isFeature1Enabled(): bool
{
return $this->feature1_enabled;
}
public function isFeature2Enabled(): bool
{
return $this->feature2_enabled;
}
}
Then I would extend that class for each Domain and set the overrides that are needed for that domain:
Class Domain1 extends Features {
// override
protected $feature1_enabled = false;
}
Then create a Middleware to bind the Features Class to the container:
class AssignFeatureByDomain
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
switch ($_SERVER['HTTP_HOST']) {
case 'domain1':
app()->bind(Features::class, Domain1::class);
break;
default:
abort(401, 'Domain rejected');
}
return $next($request);
}
}
Don't forget to attach this middleware to your routes: to a group or for each route.
After this you can TypeHint your Features class in your controllers:
public function index(Request $request, Features $features)
{
if ($features->isFeature1Enabled()) {
//
}
}
Laravel is great with this, you can even store your features in db, and create a relation between the domain.
I would recommend to use Gates and Policies, which will give you better control in your controllers and blade templates. This means you register the gates from your db or hard code them.
For example if you have export products feature with a button in your system and you want to make that feature available to some users you can register gates with business logic.
//Only admins can export products
Gate::define('export-products', function ($user) {
return $user->isAdmin;
});
Then you can do the following in the controllers
<?php
namespace App\Http\Controllers;
use App\Product;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class ProductsController extends Controller
{
/**
* Export products
*
* #param Request $request
* #param Post $post
* #return Response
* #throws \Illuminate\Auth\Access\AuthorizationException
*/
public function export(Request $request)
{
$this->authorize('export-products');
// The current user can export products
}
}
Here is an example for your blade templates:
#can('export-products', $post)
<!-- The Current User Can export products -->
#endcan
#cannot('export-products')
<!-- The Current User Can't export products -->
#endcannot
more information available at https://laravel.com/docs/5.8/authorization
Interesting case you have here. It might be interesting to look into a Feature interface or abstract class that contains a few methods you generally need.
interface Feature
{
public function isEnabled(): bool;
public function render(): string;
// Not entirely sure if this would be a best practice but the idea is to be
// able to call $feature->execute(...) on any feature.
public function execute(...);
...
}
You could even devide these into ExecutableFeature and RenderableFeature.
Further on some kind of factory class could be made to make life easier.
// Call class factory.
Feature::make('some_feature')->render();
...->isEnabled();
// Make helper method.
feature('some_feature')->render();
// Make a blade directives.
#feature('some_feature')
#featureEnabled('some_feature')
What I did in my case was creating a new table on the database, you could call it Domains for instance.
Add all the specific features, those which could be shown on some domains but not in the rest, as columns for that table as bit for boolean values. Like, in my case, allow_multiple_bookings, use_company_card... whatever.
Then, consider creating a class Domain and its respective repository, and just ask these values on your code, trying to push as much as possible that logic into your domain (your model, application services, etc).
For instance, I would not do the check on the controller method for RequestBooking if the domain which is requesting a booking can request only one or more.
Instead I do it on a RequestBookingValidatorService which can check if the booking datetime has passed, the user has an enabled credit card, ... or the Domain which this action comes from is allowed to request more than one booking (and then if it already has any).
This adds the convenience of readability, as you have pushed this decision to your application services. Also, I find that whenever I need a new feature I can use Laravel (or Symfony) migrations to add that feature on the table and I could even update its rows (your domains) with the values I want on the same commit I coded.

Using adapter pattern when consuming 3rd party APIs and creating a domain in Laravel

In my Laravel REST API project I mainly consume 3rd party APIs. For that, I have a 'Services' folder grouped by APIs (Accommodation, Planning, Discount etc) to send correct parameters to APIs and get the raw data.
I feel that I need to use adapter pattern here, because this 3rd party outputs need to be formatted.
Let me try to give an example.
I have an EventDao interface (Data access object) and one or multiple concrete EventDao classes like EventbriteDao.
I also have an adapter for each concrete DAO. e.g: EvenbriteAdapter
I will have some business logic somewhere so I need to have an Event entity class. To pass the adapter's data to the entity, I need an EventDTO class (data transfer object)
Finally I can call the eventDao (via interface thanks to Laravel's service providers)
I pass its raw output to the adapter, then adapter's output to the entity. Then I can call one of methods of the entity class. (After that I need to convert it to a proper json data, but it is the easy part.)
I don't get where to put other CRUD logic like updateEvent, deleteEvent, getAll etc. Should I call them directly in controller or create repositories (the repository pattern)? I am confused about it.
Would it be a good approach or over-engineering? Because I have 5-6 classes/interfaces other than controller.
Another problem is calling EventbriteAdapter directly in the controller. Should I have an interface for it? In this case I will need to bind both service and adapter interfaces to its implementations in AppServiceProvider.
My another concern is having collections for entity chunks. If I call getAll() method I can loop through the data and create an array of objects, but I am not comfortable with it. Laravel's collections would be useful, but I want to separate application layer from domain. What would be a good solution for it?
Here example codes for some of the files I mentioned are:
interface EventAdapter
{
public function getId();
public function getName();
public function getStartDate();
public function getLocationName();
}
class EventbriteAdapter implements EventInterface
{
private $raw;
public function __construct(array $raw)
{
$this->raw = $raw;
}
public function getName()
{
return $this->raw['name'];
}
public function getStartDate()
{
return $this->raw['start'];
}
public function getLocation()
{
return $this->raw['venue']['name'].' '.$this->raw['venue']['address'];
}
}
// Fetch event from Eventbrite (or other third-party)
$result = fetchEventFromEventbrite();
// Wrap event in adapter
$adapter = new EventbriteAdapter($result);
I don't get where to put other CRUD logic like updateEvent,
deleteEvent, getAll etc. Should I call them directly in controller or
create repositories (the repository pattern)? I am confused about it.
You can use the Gateway pattern to encapsulate all logic of interaction with 3rd party API. The gateway can contain methods to get data and save data. For example:
interface EventGatewayInterface
{
/**
* Get an event by id
*
* #param mixed $id unique identifier of an event
* #return Event the event
*/
public function getById($id);
/**
* Get all events
*
* #return Event[] list of events
*/
public function getAll();
/**
* Add an event
*
* #param Event $event the event which will be added
*/
public function add(Event $event);
/**
* Update an event
*
* #param Event $event the event which will be updated
*/
public function update(Event $event);
/**
* Delete an event
*
* #param Event $event the event which will be removed
*/
public function delete();
}
Would it be a good approach or over-engineering? Because I have 5-6
classes/interfaces other than controller.
In fact, you use the Adapter pattern to translate one representation (raw representation) to another (object representation). But the Adapter pattern is used to translate one program interface into a compatible program interface. To convert representations used the Mapper pattern. You can implement simple mapper for example:
class RawEventMapper
{
/**
* Map raw data to an event object
*
* #param array $data raw data
* #return Event the event object
*/
public function map(array $data)
{
$event = new Event();
$event->name = $data['name'];
$event->startDate = $data['start'];
$event->location = $data['venue']['name'].' '.$data['venue']['address'];
return $event;
}
}
and use it in Gateway to convert raw data to an object.
class ConcreteEventGateway implement EventGatewayInterface
{
/** #var RawEventMapper data mapper */
protected $mapper;
/**
* Constructor
*
* #param RawEventMapper $mapper data mapper
*/
public function __construct(RawEventMapper $mapper)
{
$this->mapper = $mapper;
}
/** #inheritdoc */
public function getById($id)
{
// get raw data from 3rd party API
return $this->mapper->map($raw);
}
}
Laravel's collections would be useful, but I want to separate
application layer from domain. What would be a good solution for it?
If you aim to create a domain layer independent on the framework you shouldn't use Laravel collection.

How to add an Action to Account Controller in Shopware

How to add a custom action to an existing Controller in Shopware?
Examples (url structure):
/account/bonus
/account/custom
/account/...
Usually it's easier and cleaner to create a new controller for that purpose, but in some cases it's necessary.
You should not replace the "account" controller.
You can define you own action for existing controller with following:
public static function getSubscribedEvents()
{
return [
'Enlight_Controller_Action_Frontend_Account_MyBonus' => 'onAccountMyBonus',
];
}
and then
public function onAccountMyBonus(\Enlight_Event_EventArgs $args)
{
$args->setProcessed(true);
.....
your code here
}
Spoiler: Replace the controller
There is no cleaner way than to replace the whole controller and extend it's functionality, so it's nearly as clean as Shopware's hooks.
Guide
Add a new Subscriber to your Plugin
class AccountSubscriber implements SubscriberInterface
{
/**
* #return array
*/
public static function getSubscribedEvents()
{
return array(
'Enlight_Controller_Dispatcher_ControllerPath_Frontend_Account' => 'getAccountController'
);
}
/**
* #return string
*/
public function getAccountController()
{
return $this->getPath() . '/Controllers/Frontend/AccountExtended.php';
}
/**
* #return string
*/
public function getPath()
{
$plugin = Shopware()->Container()->get('kernel')->getPlugins()['AcmeYourPlugin'];
return $plugin->getPath();
}
}
Downsides
Unfortunately some controller have private methods which impact the logic. Like the Account Controller. So it's not always possible to simply extend the controller.
In the end, try to add a new controller with a new route.
It's easier, and cleaner.
There is a cleaner way than replacing the whole Controller.
It is also not recommended to replace a whole controller due to the lack of update compatibility.
In the worst case something like that could kill the whole website.
A while ago I created a thread in the shopware forum (german) discussing the exact same issue. I wanted to extend an existing finishAction() in the checkout Controller.
public function onPostDispatchCheckout(\Enlight_Controller_ActionEventArgs $args)
{
/** #var \Enlight_Controller_Action $controller */
$controller = $args->getSubject();
/** #var \Enlight_Controller_Request_Request $request */
$request = $controller->Request();
if ($request->getActionName() !== 'finish') {
return;
}
// do your stuff here
}
So even though it is not the exact same issue you have, the procedure is quite the same.
First off you subscribe to the controller (in my case the PostDispatchCheckout Controller) afterwards you edit the controller in your Bootstrap.php
To make sure, that it just alters a specific action you have to use the if-construction so your code gets just triggered on the wished action [in my case the finishAction()].
I hope this helps. What wonders me though is why you have to add a new action to an already existing controller. I can think of no situation where something like that is more practicable than creating a complete new custom controller.
Kind regards,
Max

Different state for Eloquent model fields depending on current user in laravel

I have the model:
class Task extends Model {
}
with some fields
protected $fillable = ['message', 'due_time', 'status', 'etc...'];
I've added custom function:
public function getEditableStateFor{AttributeName}
In my helper function I check that if
method_exists($class, 'getEditableStateForField1')
than I allow to edit this field depending on boolean value returned from this function.
Example:
if( ! $class->getEditableStateForField1() ) {
return "You can not edit field field1";
}
Here is how looks like some functions in Task:
private function isCreator() {
$user = Auth::user();
if($user) {
return $user->id === $this->creator_id;
}
return false;
}
public function getEditableStateForMessage() {
return $this->isCreator();
}
public function getEditableStateForDueTime() {
return $this->isCreator();
}
Is this a good way to do it or it is very bad design because of hidden dependency on Auth::user()?
What is a better way?
I do not want to put this logic inside controllers because this logic propagates to another models and is universal across application.
I'm like you and like to have Models that contain as much of the business logic as possible while remaining totally free of depencies on the "web" part of the application, which I believe should stay in Controllers, Request objects, etc. Ideally, Models should be easily usable from command line interfaces to the application, from within the Tinker REPL, and elsewhere while still guaranteeing data integrity and that business rules are observed.
That said, it seems the Laravel creators had slightly different ideas, hence the Auth facade being easily available in the model.
What I would likely do is add a parameter of type User to the getEditableStateFor series functions, and then in turn pass that parameter to isCreator ($user) and elsewhere. That also frees you up to be able to allow associated users to edit each other's Tasks if that ever became a desired feature in the future.
Edit: another, perhaps better or perhaps worse, is to have an instance method like setCurrentUser ($user) then use setFieldNameAttribute methods so that the controller doesn't have to check the editability of fields, keeping that the model's responsibility. Then you could call the getEditableStateFor methods, which now check for the current user set by the above method (maybe falling back to Auth::user() or throwing a helpful error), inside the setter.

Laravel Bind Multiple Class to One Contract in The Service Provider

So what I am trying to do is have my eccomerce site handle both Paypal and Stripe payments. However, I am not sure how this is done.
This is what I have.
class BillingProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
$this->app->bind('App\Contracts\BillingInterface','App\Services\Billing\PaypalBilling');
}
}
This works fine if I only need Paypal. However, I need both Paypal and Stripe.
Any idea how we can go about implementing this? So when we typehint this we can either get paypal or stripe.
public function stripe(Request $request, BillingInterface $bill){// Handle stripe payment.}
public function paypal(Request $request, BillingInterface $bill){// Handle paypal payment.}
Imho, there are many ways to do it.
First of all, take a look to the contextual binding of the Service Container. If you're using different classes on your checkout procedure, you can set a resolve strategy based on who is actually using the contract.
However, I would probably choose something different.
Let's apply the strategy design pattern for this.
Basically, in two separate steps:
create a "top" class named, for example, BillingManager;
a class for each payment type (imho, make a paypal() and a stripe() method in a single class is wrong because of this) that implement your billing interface. Let's say that this interface has a 'process($orderId)` method;
Now, the BillingManager class will be called. Probably, you will call a general method pay that will take, as a parameter, something to understand what strategy it will use.
Something like
public function pay($strategy, $orderId) {
// use $strategy to understand which service must be used.
// very raw example:
$strategy = app()->make($strategy . 'Strategy');
$strategy->process($orderId);
}
Of course, you will need a safe mechanism to understand what service you will need to use. After that, you will be able to use the BillingManager class every time, with many different payment systems, without worry about anything else.

Resources