欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Laravel中注册Facades的步骤详解

程序员文章站 2023-12-12 20:25:04
本文讲述了laravel中注册facades的步骤。分享给大家供大家参考,具体如下: 在laravel中将类注册为fcade可以使用ioc容器,每次使用这个类的时候只会初...

本文讲述了laravel中注册facades的步骤。分享给大家供大家参考,具体如下:

在laravel中将类注册为fcade可以使用ioc容器,每次使用这个类的时候只会初始化一次类,类似单例模式,而且可以像使用静态方法调用类的方法,下面是在laravel中注册facades的步骤。

1.在项目app目录的providers/appserviceprovider.php中的register方法新增方法,代码如下。

/**
 * register any application services.
 *
 * @return void
 */
public function register()
{
 $this->registertestmodel();
}
private function registertestmodel()
{
 $this->app->singleton('testmodel', function ($app) {
  $model = 'app\models\test';
  return new $model();
 });
 $this->app->alias('testmodel', 'app\models\test');
}

这里把命名空间是app\models的test类注册为单例模式,并且取个别名testmodel.这个test类的文件位置app/models/test.php.

2.建立一个facade类

在项目根目录app\facades目录新增文件,如test.php,代码如下,目录不存在可以新建一个。

<?php
namespace app\facades;
use illuminate\support\facades\facade;
class test extends facade
{
 /**
  * get the registered name of the component.
  *
  * @return string
  */
 protected static function getfacadeaccessor()
 {
  return 'testmodel';
 }
}

通过继承facade,重载getfacadeaccessor方法,返回之前绑定的单例模式的类的别名。

3.使用facade

经过前面的步骤后,可以使用test这个facade了,如下示例是在控制器中使用facade的方式。

<?php
namespace app\http\controllers;
use app\facades\test;
use illuminate\routing\controller;
class testcontroller extends controller
{
 public function __construct()
 {
  test::show();
  test::show();
 }
}

先看看这个原始类test.php的内容:

<?php
namespace app\models;
use illuminate\database\eloquent\model;
class test extends model
{
 protected $table = 'tt';
 public static $times = 0;
 public function __construct()
 {
  self::$times++;
  parent::__construct();
 }
 public function show()
 {
  echo self::$times . '<br>';
 }
}

经过注册facade后,调用show方法就是test::show()的形式,并且类似单例模式不会多次实例化,调用也十分简单。

ps:以上仅为注册facade的方法和步骤,实际项目中可能还需对model层进行进一步的封装。

转自:小谈博客 http://www.tantengvip.com/2016/01/laravel-facades-register/

更多关于laravel相关内容感兴趣的读者可查看本站专题:《laravel框架入门与进阶教程》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家基于laravel框架的php程序设计有所帮助。

上一篇:

下一篇: