Laravel - To have a unique function of creation of the entity

Asked

Viewed 201 times

1

After seeing a lot on the internet, I understood that I should not call a function of one controller in another and that the solution but elegant is to create a service, but I did not understand how I create the service and much less how I call its functions.

What I need to do is that when creating a simulated, I create a proposal and link to this simulated, but I already have a place that I create this proposal, in her contralator:

public function create(Request $proposta)
    {
        $this->valida($proposta);
        $uuid = Str::uuid();

        //load file
        $file = $proposta->file('file');

        // s3 storage
        Storage::disk('s3')->putFileAs(
            'proposta/',
            $file,
            $uuid . $file->getClientOriginalExtension(),
            [
                'visibility' => 'public',
                'mimetype' => 'application/pdf'
            ]
        );

        //get sotarege url
        $url = ('https://meuprovedor/proposta/' . $uuid . $file->getClientOriginalExtension());

        $prop = Proposta::create([
            'nome' => $proposta['nome'],
            'numero' => $proposta['numero'],
            'url' => $url,
            'escola_id' => $proposta['escola_id'],
            'grade_id' => $proposta['grade_id'],
        ]);

//        Log::error(print_r($proposta['videos'],true));
//        Log::error(print_r(json_decode($proposta['videos']),true));

        foreach (json_decode($proposta['videos']) as $video) {
            Video::create([
                'ordem' => $video->ordem,
                'titulo' => $video->titulo,
                'video_url' => $video->video_url,
                'proposta_id' => $prop->id
            ]);
        }

        return response()->json("Prosposta Criada", 200);
    }

Now in my role that creates my simulation I need to create a proposal passing my request and get the id of the created proposal to move to creating the simulation (there in the commented part):

 public function create(Request $simulado)
    {
        $this->valida($simulado);

        $pieces = explode('T', $simulado->data);

        return new SimuladoResource(Simulado::create([
            'data' => Carbon::createFromFormat("Y-m-d", $pieces[0]),

            'escola_id' => $simulado['escola_id'],
            'proposta_id' => //função que cria uma proposta e retorna o id,
        ]));
    }

my question is: Is there a php Artisan command to create this service? I just create it and then create a function inside and importing the file into my controllers I can already call the function? I ask this because in the references of Laravel, talks to create an interface, Register and a lot of other things, I do not understand what I have to do to have a unique function that tando the create of the proposal uses, when the create of the simulated use.

  • Service they say is any class that performs some logic. There are those who abuse the use of Service by laziness to correctly name that logic. In a way, you are already using a "service" within your controller with the $this->valida() method, the difference being that it would be in a separate class, roughly speaking. Moving this method to an Laravel Form Request, for example, would be as close as I can think of as an analogy to a service.

  • Also, try to better organize the steps to create your entity. What they have in common is the logic to upload to S3? Extract and name this to reuse elsewhere if it makes sense.

  • If you can also post the references you consulted, it also helps to understand how you imagined to solve this problem.

1 answer

2


What I imagine is that you may have got confused with the idea of Service, Service Container and Service Provider. Regardless of being or not, without going into too much detail, but enough:

What you can do is create a class to encapsulate this logic and invoke in the Controller you need. There is no command to create this class, the way to build it is manually, as you already know it: a file for a class, named with the class name. Don’t forget the namespace! Yes, actually try to encapsulate your business logic to the maximum, removing what you can from the controller. When creating your service class, it should work in the "Service Container" of Laravel that uses Control Inversion and Dependency Injection. The service container is a class that creates an object to create other objects. You might also have asked about Artisan’s command to "create service" because you have searched for "service providers" and believing that these were the service classes.

In reality, service providers are a means of teaching the service container, the way it should instantiate a service object. You will not implement your logic in the Service Provider class, but will use it to register your service and/or manipulate it. [ That is, that class you manually created before and implemented the methods you needed, with its encapsulated business logic. ]

For example, in the case of a functional service record: suppose you have created your Service class to make simulated, called "Simuladoservice". Hence you want to use some methods of this class within your controller, maybe even a method called create(). But then you think, I need to pass parameters in creating this service, how to do? Suppose you created a Laravel mobile service to teach the service container to instantiate Simuladoservice, using the terminal command:

php artisan make:provider SimuladoServiceProvider

Then, this class that was generated would come with two default methods: Register and boot. You should use Register() to register your service class, for example, in this way:

public function register()
{
    $this->app->bind(SimuladoService::class, function($app, array $parameters) {
        return new SimuladoService($parameters[0], $parameters[1], $parameters[2]);
    });
}

Each index in the Parameters array will correspond one of the parameters being passed to Simuladoservice. Then just go there in your controller and call this service using the app helper:

$service = app()->make(SimuladoService::class, [$parametro1, $parametro2, $parametro3]);
$service->create($parametro);

Of course, all of this will work after registering your new Provider service in the config/app.php file. Obviously, the parameters are fictitious in relation to their implementation. But I believe you must have understood the idea!

This is a way to use services you have created, using Laravel’s service container. When you have practice, they will look very stylish.

[]'s

Browser other questions tagged

You are not signed in. Login or sign up in order to post.