Laravel Create Function to be used in different Controllers/in the same Controller - laravel

It's more a general question, I want someone to point me to the direction I should go.
1) FUNCTION FOR SAME CONTROLLER: I have two methods: Store and Update in the same controller. They both should contain some complex request validation (which I can't do via validator or form request validation because it's too complex). This means for me now using the same code twice in two methods... How can I take this code, create a function and use it in both Store and Update methods just with a single line, like:
do_this_function($data);
2) FUNCTION FOR DIFF. CONTROLLERS: I have another code which I use in many different Contollers. It transliterates Russian letters into Latin ones ('Сергей' = 'Sergey' and so on). How and where should I register this function to be able using it in different Contollers?
transliterate_this($data);
I have read something about helpers. Should I use them? If you an experienced Laravel develper and say so, I will read everything about them. Or, if you advice something else - I'll read about that.:) I just don't want to spend time reading about something useless or "not right way to-do-it".
Appreciate any help!

1) You could create a form request validation or you could just create a private function that would handle the validation and return the result.
2) You can create a helpers.php file, see here, and you put your translation function inside. Then you can call it from anywhere:
In a controller transliterate_this($data);
In a view {{ transliterate_this($data); }}.

You can do complex validation even inside a FromRequest. You can override the getValidatorInstance for example, or any other method from the base class to plug your validation logic on top of the basic validation rules. Else just consider making an external class to handle that complex validation and inject it in your controllers using Laravel's IoC container.
You should create a facade to provide that feature. Then you can easily use it anywhere (and additionally create a helper method for it if that makes you feel better). Something like Transliterate::toLatin($str)

everyone! Thank you all for great answers. But I have discovered that the problem was that I didn't know anything about Object-Oriented Programming.
(Ans I was working in Laravel:)).
After I took an Object Oriented Bootcamp from Laracasts, I started 'seeing' how Laravel actually works and I know can easily create methods inside classes and use them in other classes.
https://laracasts.com/series/object-oriented-bootcamp-in-php
(of course, you can read something else on OOP, but Jeffrey Way has really outstanding explanation talent!)

Related

Best practice for simple Laravel model operations

Let's say I'm writing a Laravel controller that has a function: make a simple search on a model and do anything with the result. Something like this (without any validation, for simplicity):
public function search($name)
{
$person = Persons:where('name', $name)->first();
doSomethingWith($person);
// ...
}
Should I move this tiny Eloquent code to the Person model in a dedicated function?
Usually I write all the "complex" operations to the Models to have short and readable controllers, but when I have to do little operations like this I always find that moving a single line of code (even if it is directly related to the database) into a separated model function will bring too much overhead to my code.
A controller should be free of business logic.
In your case, I don't see business logic in the first line
$person = Persons:where('name', $name)->first();
I don't see any reason to write unit tests for this line, so there is no lack of domain knowledge to the controller and you can leave it in the controller
You could follow this MVC pattern with more patterns. You could learn more about this from here: DevSkill. Make sure you watch the video with subtitle, cause it's a Bangladeshi Language video. That's why subtitle will help you to understand the standard MVC pattern software development. Actually, I am also following this convention to develop software with Laravel 🙂

Which is better in codeigniter? Adding a function in a helper or adding a function in an extended base class

In a codeigniter project i have to do some set of stuff in one than one controller.
I code all that stuff in a function and now i need to call whenever necessary.
i think Writing this function in more than one controller is not good.
i have 2 options,
create a helper and write these function in that and include the helper in necessary controllers.
Since i have extended CI base controller (My_Controller) and most of my controllers are extended that controller, i can write this function to my base controller also.
I have confused which one is better, right way?
Which one will speed up the process?
Is the second way slows the site?
They are identical for all intents and purposes.
Using a helper allows you to make the code portable, so you can use it in other projects, or to be called from anywhere in the code base, in the case of a formatting function for example
If you were planning to put it in a controller, then MY_Controller is best bet
Just to help you on you endeavor what i do is: (this is just me)
If i need to use something in the views, i use a helper a custom one or built in.
If i want to do something on a controller that other controller will be using too and don't want it to mess up or crowd my controller i use a library (pretty much you can use a helper but i chose to use a library)
If i want to load lets say a method, to affect Globally or some of the controller i use the base controller. (you could also use helper or library)
The key is you are not restricted to one, choose the best that suits you, as the saying goes, there are many ways to skin a cat, but please don't skin a cat..

Is it possible to call directly from a model method from another model of the same component

Is it possible to call directly from a model method from another model of the same component?
Is there any default Joomla option to call in such a way.
Yes You can
It will not break MVC architecture,
You can check like this
if(!class_exists('VirtueMartModelUser')) require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'user.php');
$usermodel = VmModel::getModel('user');
$currentVMuser = $usermodel->getUser();
First you should include the model file in the required model then create the object.
then call like above.
This example is Virtue-mart using method
According to the my knowledge NO. Otherwise it will break the MVC architecture.
What you can do is
Replicate the function you want to use.
Make the call from the controller to the both method.
My Advice is to you is even if you figure out a way to do it, Don't do it. It will mess up your whole architecture.
If you have any issues please ask.

what is the best structure for a project in codeigniter and how to use it?

I have some weeks since im using CI, but now I've found some problems about the structure of my project, I would like someone to give me some clues because I am kinda stuck, the problem is this:
I have my project MVC, so, I am dividing it into files (each per functionality) for example, there is a file with all the functions corresponding at login, and other with all related at post (it's an example), but now I am on a moment where I need to use login or posting into another part of the project, reading I found out i cannot call a controller from another, I can use the helper but still I will need to use a model, so I have to take that code and paste it into the controller where I'm calling the model and so on (and it's not good), I found out I can use modules, still I don't want to go over them until someone could give me an experience of this, i wouldnt like to change the project, is any way I could run all those controllers (i know i can use run:: I'm not sure if i can send parameters in it), any ideas please?
Thanks in advance.
Fair warning, this type of question will get shot down by many SO moderators, but I'll give you some tips regardless:
Controller actions are single-use. If you find yourself with duplicate code in multiple controllers (or, needing to call a controller function from another controller), that's a sure sign you should move that code to a model or library.
Models are object-specific, not action-specific. I wouldn't have a model dedicated to logins, unless you have multiple types of logins (most apps/sites just have member logins, but you might have administrators, etc. that are stored in a different table from the rest). Instead, have a User_model class, and make function login($email, $password) a method of that class.
Controller-to-model interaction should be very concise. If you find yourself with 30 lines of code passing data back and forth between the same controller and model, you might be trying to do too much with that one controller action.
Keep your models fat, controllers skinny, and views dumb.

CodeIgniter: Decision making for creating of library & helper in CodeIgniter

After developing in CodeIgniter for awhile, I find it difficult to make decisions when to create a custom library and when to create a custom helper.
I do understand that both allow having business logic in it and are reusable across the framework (calling from different controller etc.)
But I strongly believe that the fact that CI core developers are separating libraries from helpers, there has to be a reason behind it and I guess, this is the reason waiting for me to discover and get enlightened.
CI developers out there, pls advise.
i think it's better to include an example.
I could have a
class notification_lib {
function set_message() { /*...*/}
function get_message() {/*...*/}
function update_message() {/*...*/}
}
Alternatively, i could also include all the functions into a helper.
In a notification_helper.php file, i will include set_message(), get_message(), update_message()..
Where either way, it still can be reused. So this got me thinking about the decision making point about when exactly do we create a library and a helper particularly in CI.
In a normal (framework-less) php app, the choice is clear as there is no helper, you will just need to create a library in order to reuse codes. But here, in CI, I would like to understand the core developers seperation of libraries and helpers
Well the choice comes down to set of functions or class. The choice is almost the same as a instance class verses a static class.
If you have just a simply group of functions then you only need to make a group of functions. If these group of functions share a lot of data, then you need to make a class that has an instance to store this data in between the method (class function) calls.
Do you have many public or private properties to store relating to your notification messages?
If you use a class, you could set multiple messages through the system then get_messages() could return a private array of messages. That would make it perfect for being a library.
There is a question I ask myself when deciding this that I think will help you as well. The question is: Am I providing a feature to my framework or am I consolidating?
If you have a feature that you are adding to your framework, then you'll want to create a library for that. Form validation, for example, is a feature that you are adding to a framework. Even though you can do form validation without this library, you're creating a standard system for validation which is a feature.
However, there is also a form helper which helps you create the HTML of forms. The big difference from the form validation library is that the form helper isn't creating a new feature, its just a set of related functions that help you write the HTML of forms properly.
Hopefully this differentiation will help you as it has me.
First of all, you should be sure that you understand the difference between CI library and helper class. Helper class is anything that helps any pre-made thing such as array, string, uri, etc; they are there and PHP already provides functions for them but you still create a helper to add more functionality to them.
On the other hand, library can be anything like something you are creating for the first time, any solution which might not be necessarily already out there.
Once you understand this difference fully, taking decision must not be that difficult.
Helper contains a group of functions to help you do a particular task.
Available helpers in CI
Libraries usually contain non-CI specific functionality. Like an image library. Something which is portable between applications.
Available libraries in CI
Source link
If someone ask me what the way you follow when time comes to create Helpers or Libraries.
I think these differences:
Class : In a nutshell, a Class is a blueprint for an object. And an object encapsulates conceptually related State and Responsibility of something in your Application and usually offers an programming interface with which to interact with these. This fosters code reuse and improves maintainability.
Functions : A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value. You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.
So go for Class i.e. libraries if any one point matches
global variable need to use in two or more functions or even one, I hate using Global keyword
default initialization as per each time call or load
some tasks are private to entity not publicly open, think of functions never have public modifiers why?
function to function dependencies i.e. tasks are separated but two or more tasks needs it. Think of validate_email check only for email sending script for to,cc,bcc,etc. all of these needs validate_email.
And Lastly not least all related tasks i.e. functions should be placed in single object or file, it's easier for reference and remembrance.
For Helpers : any point which not matches with libraries
Personally I use libraries for big things, say an FTP-library I built that is a lot faster than CodeIgniters shipped library. This is a class with a lot of methods that share data with each other.
I use helpers for smaller tasks that are not related to a lot of other functionality. Small functions like decorating strings might be an example. Or copying a directory recursively to another location.

Resources