D
D
Dmitry2016-06-13 13:11:34
Laravel
Dmitry, 2016-06-13 13:11:34

What is the correct way to store your own controllers and functions in Laravel?

Let's say I want to make some helper class or just a function. For example, I need a function to trim text to a certain number of words (to create news previews). There is no such function in php (there is only trimming to a certain character, but I need word-by-word trimming so that the text does not break off in the middle of a word). I wrote such a function. And now I would like that I could call this function in any controller, model and view. How can I store this function? It is necessary to create your own controller and write a static function in it, so that later you can call it in this way myclass::myfunction()... ?
It is especially important that you can call it directly in the view (the example with cropping may not be very good, because cropping is better in the model, but in some cases it is necessary to be able to call it directly in the view).
And where is it customary to store such controllers in laravel? In the same Controllers folder by creating a subfolder?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
D', 2016-06-13
@Denormalization

Laravel itself uses a separate helpers.php
file for these purposes. Nothing prevents you from creating your own similar file and adding it to autoload, then all these functions will be available from anywhere in the project.

A
Alexey Ukolov, 2016-06-13
@alexey-m-ukolov

What you want to do has nothing to do with controllers.
This is a normal class: put it in the src root or in any subdirectory (the main thing is that the namespace is correct).
You can create a ServiceProvider, but in this case, I think it's overkill.

V
Vladimir Grabko, 2016-06-13
@VGrabko

For example, I store all my classes in vendor so that they can be reused.

N
Nikolai Shvetsov, 2016-06-17
@ShNn

Create a Services folder at the top level, and add static functions there. Call it like this: ClassName::functionName();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question