Expose an object ( based on request ) for every application

Asked

Viewed 38 times

0

Oops, I don’t know if it’s possible to do what I want, but come on:

I have a Lumen api that basically reads a specific request header and parses it into a YAML file and turns it into an array, but since I use it in several different controllers and classes I made a function that receives this header and returns the array, however I am having to repeat this in every controller / class, what I want is:

Turn this "function" into something global that I can call any method / type class like this:

public function verifyemail(Cliente $cliente) {
  $email = $cliente->email
}

Where client is the function that returns me the array.

Kind of like the app() I can use anywhere:

app()->environment() == 'development' 

I think I made myself clear, if not, ask me.

  • It is not only you create the function in a separate file and then give a include in the archives?

  • But I say using some Laravel / Lumen Feature, like once I read about Services Providers but I couldn’t get it right

  • Have you considered adding this method to a Controller customized and then change all the Controllers to inherit from this class. Or just create a new class and add this function statically to that class, and add it to some Service Provider if you want to make it a Singleton.

  • The question is that Service Provider may depend on request ? because this my logic depends on the header I receive in the request

  • 1

    I believe every class you define in the Laravel has access to your helpers, soon, you would get the data from header by taking all the request data using the helper request.

  • 1

    If the Lumen does not support the helper request, you can pass the helper app in the class builder by Service Provider and save it in class. There is also the possibility to just add one binding in the AppServiceProvider, so you don’t need to create a Service Provider. Then use app(ClasseComAFunção::class) to get an instance of the class in your Controller, documentation.

Show 1 more comment

2 answers

1

Create in App/Helpers a Helper the way you need example:

<?php


namespace App\Helpers;


class ClienteHelper
{

    // Sua função estática
    static function verifyEmail(Cliente $cliente) 
    {
         $email = $cliente->email
    }
}

Then you can call any part of the code like this:

return ClienteHelper::verifyEmail($cliente_xpto);

1

guess q in this case the best solution is to put this method in the file Controller.php and then all other controllers in your application that extend this class can use this method normally.

Browser other questions tagged

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