Laravel 服务容器和服务提供者

2023-12-31

需要通过示例了解Laravel服务容器和服务提供者。


The 服务容器是我们应用程序的地方bindings被存储。和服务供应商是我们注册绑定的类服务容器。在 Laravel 的旧版本中,我们没有这些提供程序,开发人员总是询问在哪里放置绑定。答案令人困惑:“哪里最有意义。”(!)然后,Laravel 介绍了这些服务供应商供应商目录以使事情更加一致。

这是一个基本示例:

interface AcmeInterface {
    public function sayHi();
}

class AcmeImplementation implements AcmeInterface {
    public function sayHi() {
        echo 'Hi!';
    }
}

// Service Container
$app = new \Illuminate\Database\Container;

// Some required stuff that are also service providing lines 
// for app config and app itself.

$app->singleton('app', 'Illuminate\Container\Container');
$app->singleton('config', 'Illuminate\Config\Repository');

// Our Example Service Provider
$app->bind(AcmeInterface::class, AcmeImplementation::class);

// Example Usage:
$implementation = $app->make(AcmeInterface::class);
$implementation->sayHi();

如你看到的:

  • 首先,我们创建容器(在现实生活中,Laravel 在里面为我们做了这个bootstrap/app.php),
  • 然后,我们注册我们的服务(在我们的服务提供者课程,以及config/app.php),
  • 最后,我们获得并使用我们注册的服务。 (内部控制器、模型、服务等)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Laravel 服务容器和服务提供者 的相关文章

随机推荐