温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Laravel实现自动加载类的方法

发布时间:2021-02-02 14:32:08 来源:亿速云 阅读:210 作者:小新 栏目:开发技术

这篇文章将为大家详细讲解有关Laravel实现自动加载类的方法,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

Laravel如何实现自动加载类

Laravel使用的是composer的自动加载。

首先看 vendor/autoload.php文件

<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit5586036d8fdd45ae351f9a5ae924a5a3::getLoader();

代码很少,查看__DIR__ . '/composer/autoload_real.php'文件。 有一个类ComposerAutoloaderInit5586036d8fdd45ae351f9a5ae924a5a3,该类的名字比较奇特,主要为了防止重名。回到上面的代码,可以看到调用了getLoader()方法;

看一下部分代码

  if (null !== self::$loader) {
   return self::$loader;
  }

  spl_autoload_register(array('ComposerAutoloaderInit5586036d8fdd45ae351f9a5ae924a5a3', 'loadClassLoader'), true, true);
  self::$loader = $loader = new \Composer\Autoload\ClassLoader();
  spl_autoload_unregister(array('ComposerAutoloaderInit5586036d8fdd45ae351f9a5ae924a5a3', 'loadClassLoader'));

这里自动加载了当前类的loadClassLoader静态方法,该方法加载了__DIR__ . '/ClassLoader.php'文件,该文件中的类起到了整个框架类自动加载的作用。

回到autoload_real.php文件的getLoader()方法,看剩下部分代码

$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
  if ($useStaticLoader) {
   require_once __DIR__ . '/autoload_static.php';

   call_user_func(\Composer\Autoload\ComposerStaticInit5586036d8fdd45ae351f9a5ae924a5a3::getInitializer($loader));
  } else {
   $map = require __DIR__ . '/autoload_namespaces.php';
   foreach ($map as $namespace => $path) {
    $loader->set($namespace, $path);
   }

   $map = require __DIR__ . '/autoload_psr4.php';
   foreach ($map as $namespace => $path) {
    $loader->setPsr4($namespace, $path);
   }

   $classMap = require __DIR__ . '/autoload_classmap.php';
   if ($classMap) {
    $loader->addClassMap($classMap);
   }
  }

这里主要加载一些自动加载类相关的资源。

随后调用$loader->register(true);

这个方法比较重要

 public function register($prepend = false)
 {
  spl_autoload_register(array($this, 'loadClass'), true, $prepend);
 }

注册了loadClass方法,并且是放在队列的head。

查看loadClass方法

 /**
  * Loads the given class or interface.
  *
  * @param string $class The name of the class
  * @return bool|null True if loaded, null otherwise
  */
 public function loadClass($class)
 {
  if ($file = $this->findFile($class)) {
   includeFile($file);

   return true;
  }
 }

当实例化类的时候,找不到类,就自动会调用该方法,该方法加载了需要的类,这个方法十分重要。

现在看一下$this->findFile($class)方法内使用了之前getLoader()方法加载的相关资源。

现在整个Laravel框架如何自动加载类已经很明显了。每当实例化类的时候,会自动调用 ClassLoader的loadClass方法,加载需要的类。

关于“Laravel实现自动加载类的方法”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI