Rumah > rangka kerja php > Laravel > Adakah anda tahu dari mana asal $this->app dan app() Laravel?

Adakah anda tahu dari mana asal $this->app dan app() Laravel?

Lepaskan: 2021-08-11 09:04:33
ke hadapan
3062 orang telah melayarinya

Lajur tutorial laravel berikut akan memperkenalkan kepada anda bagaimana Laravel $this->app dan app() saya harap ia akan membantu rakan yang memerlukannya.

Penyahpepijatan titik putus untuk mencari fail yang sepadan, abaikan langkah kecil, hanya terangkan tindakan teras, '/' menunjukkan direktori di mana index.php berada

Alamat: indeks. php

1

$app = require_once __DIR__.'/../bootstrap/app.php';

Salin selepas log masuk

$app initialization

Path/…/bootstrap/app.php

1

2

3

$app = new Illuminate\Foundation\Application(

    realpath(__DIR__.'/../')

);//$app初始化工作

Salin selepas log masuk

$app initialization class dan pembina

1

2

3

4

5

6

7

8

9

10

11

12

class Application extends Container implements ApplicationContract,HttpKernelInterface

{

    //继承Container类,Container类实现应用契约接口与请求接口

    public function __construct($basePath = null){

       if ($basePath) {//$basePath = '/../'

           $this->setBasePath($basePath);//路径绑定

       }

       $this->registerBaseBindings();//基础绑定

       $this->registerBaseServiceProviders();//注册基础服务提供者

       $this->registerCoreContainerAliases();//注册别名

    }

}

Salin selepas log masuk

Pengikatan laluan

1

2

3

4

5

6

7

8

9

10

11

12

Application的setBasePath(’/…/’)方法调用Container的instance(a b s t r a c t , abstract,abstract,instance)方法赋值Contaienr类instances

instances: array:9 [▼

“path” => “\var\www\app”

“path.base” => “\var\www”

“path.lang” => “\var\www\resources\lang”

“path.config” => “\var\www\config”

“path.public” => “\var\www\public

“path.storage” => “\var\www\storage”

“path.database” => “\var\www\database”

“path.resources” => “\var\www\resources”

“path.bootstrap” => “\var\www\bootstrap”

]

Salin selepas log masuk

Pengikatan asas

Tambah pengikatan pada contoh Bekas

1

2

3

4

5

6

7

8

9

"app" => Application {#2}

  "Illuminate\Container\Container" => Application {#2}

  "Illuminate\Foundation\PackageManifest" => PackageManifest {#4 ▼

        +files: Filesystem {#5}

        +basePath: "\var\www"

        +vendorPath: "\var\www\vendor"

        +manifestPath: "\var\www\bootstrap\cache\packages.php"

        +manifest: null

    }

Salin selepas log masuk

apl Dengan Bekas menunjuk kepada contoh semasa

PackageMainfest ialah contoh pengurusan pakej Dalam kaedah pembinaan, fail mendaftarkan contoh sistem fail

mendaftarkan penyedia perkhidmatan asas

1

2

3

4

5

6

7

//class Application

protected function registerBaseServiceProviders()

{

    $this->register(new EventServiceProvider($this));

    $this->register(new LogServiceProvider($this));

    $this->register(new RoutingServiceProvider($this));

}

Salin selepas log masuk
<. 🎜>Peristiwa, Log dan Perkhidmatan asas Laluan mewarisi ServiceProvider Semasa pemulaan, atribut aplikasi diberikan kepada contoh Aplikasi

1

2

3

4

5

//class ServiceProvider   

public function __construct($app)

{

    $this->app = $app;

}

Salin selepas log masuk
Laksanakan kaedah Daftar kelas Aplikasi

1

2

3

4

5

6

7

8

9

10

11

12

13

14

//Application

public function register($provider, $options = [], $force = false)

{

    if (is_string($provider)) {

        $provider = $this->resolveProvider($provider);

    }

    if (method_exists($provider, &#39;register&#39;)) {

        $provider->register();//赋值bindings

    }

    //将服务提供者添加到serviceProviders属性队列

    //将服务提供者类名添加到loaderProviders属性

    $this->markAsRegistered($provider);

    return $provider;

}

Salin selepas log masuk
Menyediakan dua kaedah untuk pendaftaran pembekal;

Satu ialah contoh langsung nama kelas rentetan,

Satunya ialah melaksanakan kaedah $$provider->register() untuk mendaftar,

sedang melaksanakan kaedah kedua,

Lihat kembali kaedah daftar bagi contoh EventServiceProvider semasa

1

2

3

4

5

6

7

8

public function register()

{

    $this->app->singleton(&#39;events&#39;, function ($app) {

        return (new Dispatcher($app))->setQueueResolver(function () use ($app) {

            return $app->make(QueueFactoryContract::class);

        });

    });

}

Salin selepas log masuk
Panggil kaedah tunggal bagi contoh Aplikasi

1

2

3

4

5

//class Continer

public function singleton($abstract, $concrete = null)

{

    $this->bind($abstract, $concrete, true);

}

Salin selepas log masuk
Panggil kaedah bind dan tetapkan pengikatan

1

2

3

4

5

6

7

8

9

10

11

//class Container

public function bind($abstract, $concrete = null, $shared = false)

{

    if (is_null($concrete)) {

        $concrete = $abstract;

    }

    if (! $concrete instanceof Closure) {

        $concrete = $this->getClosure($abstract, $concrete);

    }

    $this->bindings[$abstract] = compact(&#39;concrete&#39;, &#39;shared&#39;);

}

Salin selepas log masuk
Kembali ke kaedah Daftar kelas Aplikasi dan laksanakan markAsRegistered($provider)

1

2

3

4

5

6

//class Application

protected function markAsRegistered($provider)

{

    $this->serviceProviders[] = $provider;

    $this->loadedProviders[get_class($provider)] = true;

}

Salin selepas log masuk
LogServerProvider dan RoutingServiceProvider are serupa

Alias ​​​​binding

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

//class Application

public function registerCoreContainerAliases()

{

    foreach ([

        &#39;app&#39;                  => [self::class, \Illuminate\Contracts\Container\Container::class, \Illuminate\Contracts\Foundation\Application::class,  \Psr\Container\ContainerInterface::class],

        &#39;auth&#39;                 => [\Illuminate\Auth\AuthManager::class, \Illuminate\Contracts\Auth\Factory::class],

        &#39;auth.driver&#39;          => [\Illuminate\Contracts\Auth\Guard::class],

        &#39;blade.compiler&#39;       => [\Illuminate\View\Compilers\BladeCompiler::class],

        &#39;cache&#39;                => [\Illuminate\Cache\CacheManager::class, \Illuminate\Contracts\Cache\Factory::class],

        &#39;cache.store&#39;          => [\Illuminate\Cache\Repository::class, \Illuminate\Contracts\Cache\Repository::class],

        &#39;config&#39;               => [\Illuminate\Config\Repository::class, \Illuminate\Contracts\Config\Repository::class],

        &#39;cookie&#39;               => [\Illuminate\Cookie\CookieJar::class, \Illuminate\Contracts\Cookie\Factory::class, \Illuminate\Contracts\Cookie\QueueingFactory::class],

        &#39;encrypter&#39;            => [\Illuminate\Encryption\Encrypter::class, \Illuminate\Contracts\Encryption\Encrypter::class],

        &#39;db&#39;                   => [\Illuminate\Database\DatabaseManager::class],

        &#39;db.connection&#39;        => [\Illuminate\Database\Connection::class, \Illuminate\Database\ConnectionInterface::class],

        &#39;events&#39;               => [\Illuminate\Events\Dispatcher::class, \Illuminate\Contracts\Events\Dispatcher::class],

        &#39;files&#39;                => [\Illuminate\Filesystem\Filesystem::class],

        &#39;filesystem&#39;           => [\Illuminate\Filesystem\FilesystemManager::class, \Illuminate\Contracts\Filesystem\Factory::class],

        &#39;filesystem.disk&#39;      => [\Illuminate\Contracts\Filesystem\Filesystem::class],

        &#39;filesystem.cloud&#39;     => [\Illuminate\Contracts\Filesystem\Cloud::class],

        &#39;hash&#39;                 => [\Illuminate\Contracts\Hashing\Hasher::class],

        &#39;translator&#39;           => [\Illuminate\Translation\Translator::class, \Illuminate\Contracts\Translation\Translator::class],

        &#39;log&#39;                  => [\Illuminate\Log\Writer::class, \Illuminate\Contracts\Logging\Log::class, \Psr\Log\LoggerInterface::class],

        &#39;mailer&#39;               => [\Illuminate\Mail\Mailer::class, \Illuminate\Contracts\Mail\Mailer::class, \Illuminate\Contracts\Mail\MailQueue::class],

        &#39;auth.password&#39;        => [\Illuminate\Auth\Passwords\PasswordBrokerManager::class, \Illuminate\Contracts\Auth\PasswordBrokerFactory::class],

        &#39;auth.password.broker&#39; => [\Illuminate\Auth\Passwords\PasswordBroker::class, \Illuminate\Contracts\Auth\PasswordBroker::class],

        &#39;queue&#39;                => [\Illuminate\Queue\QueueManager::class, \Illuminate\Contracts\Queue\Factory::class, \Illuminate\Contracts\Queue\Monitor::class],

        &#39;queue.connection&#39;     => [\Illuminate\Contracts\Queue\Queue::class],

        &#39;queue.failer&#39;         => [\Illuminate\Queue\Failed\FailedJobProviderInterface::class],

        &#39;redirect&#39;             => [\Illuminate\Routing\Redirector::class],

        &#39;redis&#39;                => [\Illuminate\Redis\RedisManager::class, \Illuminate\Contracts\Redis\Factory::class],

        &#39;request&#39;              => [\Illuminate\Http\Request::class, \Symfony\Component\HttpFoundation\Request::class],

        &#39;router&#39;               => [\Illuminate\Routing\Router::class, \Illuminate\Contracts\Routing\Registrar::class, \Illuminate\Contracts\Routing\BindingRegistrar::class],

        &#39;session&#39;              => [\Illuminate\Session\SessionManager::class],

        &#39;session.store&#39;        => [\Illuminate\Session\Store::class, \Illuminate\Contracts\Session\Session::class],

        &#39;url&#39;                  => [\Illuminate\Routing\UrlGenerator::class, \Illuminate\Contracts\Routing\UrlGenerator::class],

        &#39;validator&#39;            => [\Illuminate\Validation\Factory::class, \Illuminate\Contracts\Validation\Factory::class],

        &#39;view&#39;                 => [\Illuminate\View\Factory::class, \Illuminate\Contracts\View\Factory::class],

    ] as $key => $aliases) {

        foreach ($aliases as $alias) {

            $this->alias($key, $alias);

        }

    }

}

Salin selepas log masuk
Berikan nilai kepada atribut alias

$app core class binding

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

/…/bootstrap/app.php

/**

 *核心类绑定

 */

$app->singleton(

    Illuminate\Contracts\Http\Kernel::class,

    App\Http\Kernel::class

);

$app->singleton(

    Illuminate\Contracts\Console\Kernel::class,

    App\Console\Kernel::class

);

$app->singleton(

    Illuminate\Contracts\Debug\ExceptionHandler::class,

    App\Exceptions\Handler::class

);

Salin selepas log masuk
Panggil bind fungsi

1

2

3

4

5

//class Container

public function singleton($abstract, $concrete = null)

{

    $this->bind($abstract, $concrete, true);

}

Salin selepas log masuk
Ikat fungsi panggil balik lalai kepada nama kelas rentetan

1

2

3

4

5

6

7

8

9

10

11

//class Container

public function bind($abstract, $concrete = null, $shared = false)

{

    // If the factory is not a Closure, it means it is just a class name which is

    // bound into this container to the abstract type and we will just wrap it

    // up inside its own Closure to give us more convenience when extending.

    if (! $concrete instanceof Closure) {

        $concrete = $this->getClosure($abstract, $concrete);

    }

    $this->bindings[$abstract] = compact(&#39;concrete&#39;, &#39;shared&#39;);

}

Salin selepas log masuk
getClosure mengembalikan fungsi panggil balik lalai

1

2

3

4

5

6

7

8

9

10

//class Container

protected function getClosure($abstract, $concrete)

{

    return function ($container, $parameters = []) use ($abstract, $concrete) {

        if ($abstract == $concrete) {

            return $container->build($concrete);

        }

        return $container->make($concrete, $parameters);

    };

}

Salin selepas log masuk
Akhir sekali: mengembalikan $app

1

2

/…/bootstrap/app.php

return $app;

Salin selepas log masuk
Cadangan berkaitan:

Lima video Laravel Tutorial terbaharu

Atas ialah kandungan terperinci Adakah anda tahu dari mana asal $this->app dan app() Laravel?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Isu terkini
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan