官方文档
<code class="php"><?php namespace App\Providers; use Riak\Connection; use Illuminate\Support\ServiceProvider; class RiakServiceProvider extends ServiceProvider { /** * Register bindings in the container. * * @return void */ public function register() { $this->app->singleton('Riak\Contracts\Connection', function ($app) { return new Connection(config('riak')); }); } } </code>
这个是要自己实现吗 ?
官方文档
<code class="php"><?php namespace App\Providers; use Riak\Connection; use Illuminate\Support\ServiceProvider; class RiakServiceProvider extends ServiceProvider { /** * Register bindings in the container. * * @return void */ public function register() { $this->app->singleton('Riak\Contracts\Connection', function ($app) { return new Connection(config('riak')); }); } } </code>
这个是要自己实现吗 ?
这个是另一个package,你说的“自己实现”,其实也对的,这个地方也可以放你自己定义的class
其实这段代码产生的效果是
比如
<code>$this->app->singleton('ReportServices', function () { return new \App\Services\ReportServices(); });</code>
以后在其他class里我可以用
<code>app('ReportServices')->xxxxxx();</code>
去代替
<code>$services = new \App\Services\ReportServices(); $services->xxxxxx();</code>
Providers的存在目的就是在程序启动的时候注册各种东西,比如你要扩展Cache类去使用阿里云ocs
<code>public function boot() { //扩展阿里云OCS缓存 Cache::extend('ocs', function ($app, $config) { $prefix = $app['config']['cache.prefix']; $memcached = new \Memcached; foreach ($config['servers'] as $server) { $memcached->addServer( $server['host'], $server['port'], $server['weight'] ); if (ini_get('memcached.use_sasl')) { $user = $server['authname']; $pass = $server['authpass']; $memcached->setOption(\Memcached::OPT_COMPRESSION, false); $memcached->setOption(\Memcached::OPT_BINARY_PROTOCOL, true); $memcached->setSaslAuthData($user, $pass); } } $store = new \Illuminate\Cache\MemcachedStore($memcached, $prefix); return new \Illuminate\Cache\Repository($store); }); }</code>
比如你要扩展表单验证类
<code>public function boot() { //扩展表单验证 Validator::extend('greater_than', function ($attribute, $value, $parameters) { $other = Request::input($parameters[0]); return isset($other) && intval($value) > intval($other); }); }</code>