Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put business logic when you don't have a specified model for that feature? Laravel

I'm trying to improve my code OOP wise. I have the tendancy to put some of my bussiness logic inside my Controller.

Some people told me this is not desirable.

I know that when you are working with Posts for example. You can simply put your bussiness logic in your Post.php Model.

I now have a feature where i upload an .xlsx file and it has to be checked and validated if the format of the .xlsx is correct.

It is currently inside ScheduleController@storeDeliveryXlsx.

But i don't have a specified model for this to store the validation inside?

Is this where Repositories design pattern is needed? Or is it fine to create a model that doesn't communicate with the database like: DeliveryFile.php where i put the logic that i later can use throughout my app like this: DeliveryFile::validate($file); or DeliveryFile::upload(file);.

I think i'm likely to re-use the same validation on the .xlsx for multiple instances. So i'd like to do something like Model::validate($file);. But i don't know where to put the code.

like image 206
Rubberduck1337106092 Avatar asked Mar 06 '23 17:03

Rubberduck1337106092


2 Answers

In this case, I would personally recommend using a Service. A service class is essentially for common functionality that you may repeat across multiple controllers. The Service Layer is a design pattern that will help you to abstract your shared logic to a common service i.e. our new Service Class.

So in your instance, you could have a Service class such as ExcelValidator and then use something like the following to structure your approach.

<?php

namespace App/Services;

class ExcelValidatorService
{

  public function validate($file) 
  {
    // our validate logic
  }

}

And then in your controllers or models, you can call the ExcelValidator service to implement your repeated validate logic.

like image 82
liamjnorman Avatar answered Apr 28 '23 17:04

liamjnorman


The phrase I now have a feature would keep on repeating itself in the course of the lifetime of the code you are writing. Having separate controller, service, model classes, OOP design, modular code would definitely help in that regard. Now it might be easier, but it will keep on becoming difficult with time

like image 25
gargkshitiz Avatar answered Apr 28 '23 18:04

gargkshitiz