3
namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Bar; //Q1. where is include App\Bar?
//Q2. where is new Bar; ?


class Foo extends Controller
{

    public function foo(Request $request, Bar $bar){ //Q3. what is Bar $bar means? pass object into method?
        #1
        $this->validateLogin($request);

        #2
        $bar->barFunc();
    }   
}

I'm currently learning laravel and I notice laravel pass object into method

but I am very confuse how it works.

Here is my questions

  1. we use namespace App\Bar, where is include file? (does laravel auto include file when you use namespace?)

  2. where is new Bar; ?

  3. how foo(Request $request, Bar $bar) works?

Does it pass object into method?

why not

foo(){
    $bar = new Bar;
}
2
  • 1. They're included via composer. More on composer here. 2. There is no new Bar. At least not in your example. It's your job to pass in an instance of $bar to the function. 3. Like any other function. Type hints. And you don't do as you said $bar = new Bar directly in the function because dependency injection Commented Dec 12, 2016 at 15:28
  • Laravel uses an Inversion of Control container and it uses composer to autoload all your files for you, so you don't need to include them. Commented Dec 12, 2016 at 15:29

2 Answers 2

1

According to Laravel Docs,

See example of Implementations of PSR4 Autoloading

  • The Laravel uses type-hinting of dependencies on your controller's methods. A common use-case for method injection is injecting the Illuminate\Http\Request instance into your controller methods. See more about Dependency Injections in Controller

  • Laravel's Container is called an IOC ("Inversion of Control") Container, and that's the case because it allows your control to happen at the top level of the app: you ask in your low-level code (controllers, implementation classes, etc.) for an instance of "mailer", and the container gives you one. Your low-level code doesn't care about which service is actually sending your mail--Mandrill? Mailgun? Sendmail? It doesn't matter, as long as the interface to the mailer class is the same.

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

1

Answers:

  1. Laravel is using PSR-4 autoloading
  2. You may want to read about dependency injection and IoC
  3. Same as 2.

1 Comment

so if i add autoload inside of composer.json I don't even need to use namespace

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.