How does laravel 5 know which contract implementation I want to use? - laravel-5

I'm kind of confused of how to use contracts. I think that's because I haven't used unit-testing so that it's not obvious for me how contracts work.
Let's have look at this code:
use Illuminate\Contracts\Auth\Guard;
...
public function __construct(Guard $auth)
{
$this->auth = $auth;
$this->middleware('guest', ['except' => 'getLogout']);
}
public function postRegister(RegisterRequest $request)
{
// Registration form is valid, create user...
$this->auth->login($user);
return redirect('/');
}
So how do I know which class implements login method of contract in this line: $this->auth->login($user) ? And how can I change the class if I want to use my own?
In laravel 4 I wrote Auth::user() as an example and I used it everywhere in any controller and it worked. Now I should inject a contract inside a controller method and use it like $auth->user?
Also, If I get it right, contracts are used for making an abstraction. Okay, so, if I want to build a new interface for my own class and then have multiple classes that implement my interface, where should I write the code? I can't think of an example but lets imagine I need to implement an interface for enabling/disabling a lamp, and I have two methods like on() and off() and I have multiple ways to do that. Do I need to create new contract for that?

I hope I can make this a bit clearer for you...
Ad.1. You can check default binding at /vendor/laravel/framework/src/Illuminate/Foundation/Application.php (method registerCoreContainerAliases around line 792). If you want to create your own class or extend existing I recommend looking at How to extend Laravel's Auth Guard class? or http://laravel.com/docs/master/extending (this one is more about Laravel 4.x but might give you an idea).
Ad.2. Actually you can still use Auth::user() but I inject a contract in constructor or a method and call it like $this->auth->user or $auth->user.
Ad.3. I have a /app/Repositories folder where I put my interfaces and implementations, so to follow your example I would create subfolder Lamp and I would create LampInterface with on() and off() methods, then I would create something like Lamp.php that implements LampInterface. Next I would create a service provider in /app/Providers, like LampServiceProvider.php with binding:
namespace Apps\Providers;
use Illuminate\Support\ServiceProvider;
class LampServiceProvider extends ServiceProvider {
/**
* Register the application services.
*
* #return void
*/
public function register()
{
$this->app->singleton(
'App\Repositories\Lamp\LampInterface',
'App\Repositories\Lamp\Lamp'
);
}
}
After that I would register new service provider in /app/config/app.php and finally I can inject my interface like:
public function switchLampOn(App\Repository\Lamp\LampInterface $lamp)
{
$lamp->on();
}

Related

Laravel: When call function from another controller, the relationship query not work

I have two controllers (FirstController, SecondController) that use the same functions, to avoid rewriting them I thought of creating another controller (ThirdController) and subsequently calling the functions through it.
the problem is that if in ThirdController there are relationship query they give me the error that "they don't exist".
example:
User Model
class User extends Authenticatable implements AuthenticatableUserContract
{
use HasFactory, Notifiable;
public function comments(){
return $this->hasMany('App\Models\Comment');
}
ThirdController
class ThirdController extends Controller
{
public static function example($id){
$comments = Comment::find($id)->comments();
return $comments;
}
}
FirstController/SecondController
public function example2(Request $request){
return ThirdController::example($request->id);
When call the route it give me error:
BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::comments does not exist.
my questions are:
Is there any better method instead of creating a third controller?
Is there a solution to this?
p.s. I know I could very well build the queries without exploiting the relationship, but where's the beauty of that? :D
You do not need to create 3rd controller. You can create a class and here you write the query in a function and use this class in controller1 and controller2 by dependency injection.
First thing that's not a best practice to define a static method in one controller and call it in another controller (not recommended way).
Second you're calling Comment::find($id) with comments() relation. you should call a User class, like below snippet:
class ThirdController extends Controller
{
public static function example($id){
$comments = User::find($id)->comments();
return $comments;
}
}
RECOMEND APPROACH:
Creat a one seperate service/repository class in which you'll define a common method i.e. getUserComments() and use it in both or all of three controllers (upto your requirement/needs). By this way you implementations will be on a centric place.
If you want learn about Repository pattern you can get basic idea from: Article#1

Why won't this Laravel 5.4 service provider register?

I am trying to do a hello world service provider with the new Laravel 5.4.
I have created the following service provider file:
//File: app/TestProvider/TestServiceProvider.php
namespace App\TestProvider;
use Illuminate\Support\ServiceProvider;
class TestServiceProvider extends ServiceProvider
{
/**
* Register bindings in the container.
*
* #return void
*/
public function register()
{
$this->app->bind('Test', function ($app) {
return new Test();
});
}
}
I have created a simple class under the same namespace:
//File: app/TestProvider/Test.php
namespace App\TestProvider;
class Test
{
/**
* Register bindings in the container.
*
* #return void
*/
public function helloWorld()
{
echo "hello world";
}
}
The problem is, this is not registering. The register method is executing as when I put a breaker before the 'bind' method, it executes:
public function register()
{
dd("BREAKER");
$this->app->bind('Test', function ($app) {
return new Test();
});
}
So this outputs "BREAKER" as expected. However if I put the breaker in the closure, nothing happens which suggests for some reason, that 'bind' method isn't being executed??
Any ideas?
EDIT:
Just some further info: I know that the Test class is registered and in the correct namespace as I can do:
dd(new Test());
in the registration method, and it outputs the resource id as expected.
Explanation
The closure provided only runs when the binding is being resolved. That's why it's a closure, it can be saved in the service container and resolved at any time while the program runs.
Solution
To see the resolved binding, create a controller and resolve the class in that controller:
// File: app/Http/Controllers/TestController.php
namespace App\Http\Controllers;
// This isn't the best way, but it works. See the best way below
class TestController extends Controller {
public function index()
{
return \App::make('Test')->helloWorld();
}
}
Of course, don't forget to register the route:
// File: routes/web.php
Route::get('/', 'TestController#index');
The binding will resolve when you hit the homepage.
However, as I said, it's not the best way, so here I prepared a better way. Change the way you register the binding:
// File: app/Providers/TestProvider.php
namespace App\TestProvider;
use Illuminate\Support\ServiceProvider;
use App\TestProvider\Test;
// Better way
class TestServiceProvider extends ServiceProvider
{
/**
* Register bindings in the container.
*
* #return void
*/
public function register()
{
// Note: we bind the exact complete class name!
$this->app->bind(Test::class, function ($app) {
return new Test();
});
}
}
After this change the controller so that it looks like this:
namespace App\Http\Controllers;
use App\TestProvider\Test;
class TestController extends Controller {
/**
* #var Test $test
*/
private $test;
// Let Laravel resolve the dependency on constructing the class
public function __construct(Test $test)
{
$this->test = $test;
}
public function index()
{
return $this->test->helloWorld();
}
}
You will see that the exact same thing happens, but it looks more elegant and avoids conflicts.
Details
Laravel gives only a high level overview of the service container, which doesn't help to learn how it works on the inside. The best way to see that is to go down the call stack.
When you do that, you find that Laravel registers every class in the project in the service container. That means that whether you create a service provider or not, the class will be in the container. How exactly?
When you run php artisan optimize, Laravel creates files that have array with all the classes of the project. When you run the app, after registering everything from the service providers, Laravel registers the rest of the classes from that file.
That means that in your case, if you don't specifically register the Test class, it will still be resolvable. Basically, you only need to register classes that need some specific instructions to be resolved.
So how does Laravel resolve the dependencies?
When you run \App::make(Test::class) or inject dependency via type hinting in the constructor (the "better way" from my solution), Laravel looks for that dependency among the bindings.
When it finds the dependency, it resolves either the closure associated to it or the constructor of the class directly.
When it resolves the constructor directly, it looks for type hints among the constructor parameters and recursively resolves all of them until there's nothing else to resolve.
After that it returns the resolved class.
Of course, bear in mind that for Laravel to analyze the contructor of a class, it needs to be resolved via the service container in the first place. You can't just call $test = new Test(); and expect Laravel to do all the magic :)
Conclusion
This is a rather quick overview of Laravel's service container. The best way for you to learn it is, of course, studying the sources for yourself. It's truly elegant and it uses PHP's functionality to the fullest.
I really hope this shed some light on the service container for you and can help you in the future :)
The closure passed to the bind() method is not executed until you actually attempt to resolve the alias you are binding.
So, if you dd('breaker') inside the closure, this won't actually get executed until Test is resolved (whatever your preferred resolution method is):
Service provider:
// bind the closure to the 'Test' alias
public function register()
{
$this->app->bind('Test', function ($app) {
dd("BREAKER");
return new Test();
});
}
Code that resolve Test alias:
// different ways of resolving the alias out of the container.
// any of these will execute the bound closure.
$test = resolve('Test');
$test = app('Test');
$test = app()->make('Test');
$test = \App::make('Test');
try:
$this->app->bind(Test::class, function ($app) {
return new Test();
});

How can I override Laravel Facade methods?

I want to override the Laravels' Mail's classes facade method send (just intercept it forcing some checks and then if it passes triggering parent::send())
What is the best way to do this?
A Facade doesn't work like that. It's essentially kind of like a wrapper class that calls the underlying class that it represents.
The Mail facade doesn't actually have a send method. When you do Mail::send(), under the hood, the "facade accessor" is used to reference an instance of the Illuminate\Mail\Mailer class bound in the IoC container. It's on that object the send method is called.
The way in which you can achieve what you're after is actually a little bit trickier than it seems. What you can do is:
Write your own implementation of Mailer, extending Illuminate\Mail\Mailer, in which you can override the send method, implement your checks and call parent::send().
Write your own service provider (Extending Illuminate\Mail\MailServiceProvider), in particular re-implement the register method. It should create an instance of your own Mailer in place of Laravel's own. (You can copy most of the code from Laravel's register method).
Now, in your config/app.php file, in the providers array, replace Illuminate\Mail\MailServiceProvider::class, with your own provider.
That should let you hook into Laravel's Mail functionality.
For more information, you can take a look at the following question/answer which achieves a similar thing. It extends the Mail functionality to add a new transport driver, but it takes a similar approach in that it provides its own Mailer implementation and service provider.
Add a new transport driver to Laravel's Mailer
app/MyMailer/Mailer.php
<?php
namespace App\MyMailer;
class Mailer extends \Illuminate\Mail\Mailer
{
public function send($view, array $data = [], $callback = null)
{
// Do your checks
return parent::send($view, $data, $callback);
}
}
app/MyMailer/MailServiceProvider.php (Most of the code copied from Laravel's MailServiceProvider class)
<?php
namespace App\MyMailer;
class MailServiceProvider extends \Illuminate\Mail\MailServiceProvider
{
public function register()
{
$this->registerSwiftMailer();
$this->app->singleton('mailer', function ($app) {
// This is YOUR mailer - notice there are no `use`s at the top which
// Looks for a Mailer class in this namespace
$mailer = new Mailer(
$app['view'], $app['swift.mailer'], $app['events']
);
$this->setMailerDependencies($mailer, $app);
$from = $app['config']['mail.from'];
if (is_array($from) && isset($from['address'])) {
$mailer->alwaysFrom($from['address'], $from['name']);
}
$to = $app['config']['mail.to'];
if (is_array($to) && isset($to['address'])) {
$mailer->alwaysTo($to['address'], $to['name']);
}
return $mailer;
});
}
}
config/app.php (In the providers array)
//...
// Illuminate\Mail\MailServiceProvider::class,
App\MyMailer\MailServiceProvider::class,
//...

Laravel Bind Multiple Class to One Contract in The Service Provider

So what I am trying to do is have my eccomerce site handle both Paypal and Stripe payments. However, I am not sure how this is done.
This is what I have.
class BillingProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
$this->app->bind('App\Contracts\BillingInterface','App\Services\Billing\PaypalBilling');
}
}
This works fine if I only need Paypal. However, I need both Paypal and Stripe.
Any idea how we can go about implementing this? So when we typehint this we can either get paypal or stripe.
public function stripe(Request $request, BillingInterface $bill){// Handle stripe payment.}
public function paypal(Request $request, BillingInterface $bill){// Handle paypal payment.}
Imho, there are many ways to do it.
First of all, take a look to the contextual binding of the Service Container. If you're using different classes on your checkout procedure, you can set a resolve strategy based on who is actually using the contract.
However, I would probably choose something different.
Let's apply the strategy design pattern for this.
Basically, in two separate steps:
create a "top" class named, for example, BillingManager;
a class for each payment type (imho, make a paypal() and a stripe() method in a single class is wrong because of this) that implement your billing interface. Let's say that this interface has a 'process($orderId)` method;
Now, the BillingManager class will be called. Probably, you will call a general method pay that will take, as a parameter, something to understand what strategy it will use.
Something like
public function pay($strategy, $orderId) {
// use $strategy to understand which service must be used.
// very raw example:
$strategy = app()->make($strategy . 'Strategy');
$strategy->process($orderId);
}
Of course, you will need a safe mechanism to understand what service you will need to use. After that, you will be able to use the BillingManager class every time, with many different payment systems, without worry about anything else.

Access an object of one class in other codeigniter

I have two controller classes in my codeigniter application, say class A and B.I just want to create an object of class A and access the functions declared in class A from class B.Something like:-
class A extends someclass
{
public function function1(){
$this->load->view('welcome_message');
}
}
}
class B extends someclass2
{
protected $object;
public function __construct()
{
parent::__construct();
$this->objectA = new A();
}
}
}
I want to access the function function1 from class B using the object objectA. How can i do this?
Please help.
Thanks
well actually this is not the proper way in codeigniter. Actually when you have common functions in and you want to use them in 2 or more controllers. The best way is to create base controller in core folder with name of MY_Contoller and extend it from CI_Contoller. Write your common function in MY_Contoller. Now you have to extend all your controllers from MY_Contoller instead of CI_Contoller. You can do the same with Model.
Cross-controller access goes against CI best practice.
Either inherit both controllers from a controller that holds this common functionality (don't forget to prefix the function with '_' so it's inaccessible via url routing) or create a library that contains your re-usable functionality. A helper can also work.

Resources