p0t4t0
147
0
Laravel

Laravel custom class as service provider

Posted 1 year ago by p0t4t0

I have a class that handles API calls to an SMS API which I made manually (without using artisan). At the moment I use it to send users their activation code after they register in my RegisterController but plan to take it a step further in the future (send sms notifications when a user posts, someone comments on their post, someone private messages them)

public function create(Request $request)
{
User::create([
    'name' => $request->name,
    'email' => $request->email,
    'mobile_number' => $request->mobile_number,
    'activation_code' => $this->generateActivationCode();
    // and so on...
]);

$mySmsClass = new MySmsClass($user->mobile_number, $user->activation_code);
$mySmsClass->sendActivationCode();
} 

I was advised against this approach to avoid tight coupling in my code and was pointed in the direction of service providers. So I read a couple of articles and found that I should be doing this instead

$this->app->bind('App\MySmsClass', function() {
    return new MySmsClass();
});

and

public function create(Request $request, MySmsClass $mySmsClass)
{
User::create([
    'name' => $request->name,
    'email' => $request->email,
    'mobile_number' => $request->mobile_number,
    'activation_code' => $this->generateActivationCode();
    // and so on...
]);

$mySmsClass->sendActivationCode();
} 

But I don't see how this is going to work since my MySmsClass depends on the recently created user's mobile number and activation code.

My questions: 1.) How am I able to access the newly created user's data from my service provider? Is there a better approach?

$this->app->bind('App\MySmsClass', function() {
    return new MySmsClass($user->mobile_number, $user->activation_code);
});

2.) Where should I store my MySmsClass? Does it matter? Right now I have it just right under my app folder.

3.) I understand I have to use this to make my MySmsClass work with my Post, Comment and Inbox controllers in the future.

$this->app->when(MySmsClass::class)
          ->needs(Post::class)
          ->give(function () {
              // do something...
          });

But I'm not able to fully understand it. How will this look like in my controller when I implement it?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.