search
HomeBackend DevelopmentPHP TutorialPhalcon automatically loads (PHP automatically loads), phalcon loads php_PHP tutorial

Phalcon automatically loads (PHP automatically loads), phalcon loads php

automatically loads (phalconLoader)

Please indicate the source when reprinting

1. PHP file introduction

Through the include() or require() function, the contents of a file can be inserted into the file before the PHP program is executed.

<p>区别:<span>处理错误的方式不同</span>。<strong>include() 函数</strong>会生成一个<span><strong>警告</strong></span>(但是脚本会继续执行),而 <strong>require()</strong> 函数会生成一个<span><strong>致命错误</strong></span>(fatal error)(在错误发生后脚本会停止执行)</p>

 * Because the script will not continue execution if the file does not exist or is renamed, we recommend using require() instead of include().

2. PHP class automatic loading

Reference articles: PHP manual and PHP’s class automatic loading mechanism

Before PHP5, the loading of each PHP framework implementation class generally required a traversal of the directory according to a certain agreement to automatically load file classes or functions that meet the agreed conditions. Therefore, the use of classes before php5 was not as frequent as it is now.

After php5, when loading a php class, if the folder where the class is located is not included or the class name is wrong, the Zend engine will automatically call the __autoload function . The __autoload function needs to be implemented by the user.

After version php5.1.2, you can use the spl_autoload_register function to customize the loading processing function. When this function is not called, spl's custom spl_autoload function will be used by default.

1. PHP automatic loading __autoload

<span>function</span> __autoload(<span>$className</span><span>) {
    </span><span>$file</span> = <span>$className</span> . '.php'<span>;
    </span><span>if</span> (<span>is_file</span>(<span>$file</span><span>)) {
        </span><span>require</span>(<span>$file</span><span>);
    }</span><span>else</span><span>{
        </span><span>echo</span> 'no this ' . <span>$className</span> . ' class file'<span>;
    }
}
</span><span>$demo</span> = <span>new</span> Demo();

In fact, we can see that __autoload needs to do at least three things ("Three steps"), they are:

In the first and second steps, we must agree on the mapping method of the class name and the file. Only in this way can we find the corresponding file based on the class name. , to achieve loading.

Therefore, the most important thing in __autoload automatic loading is the corresponding relationship between the specified class name and the file in which it is located . When there are a large number of classes that need to be included, we only need to establish the corresponding rules , and then map the class names to their corresponding files to achieve Lazy loading is done.

<p><strong>Tip:</strong>spl_autoload_register() 提供了一种更加灵活的方式来实现类的自动加载。因此,不再建议使用 __autoload() 函数,在以后的版本中它可能被弃用。</p>

2. PHP automatic loading spl_autoload_register

Introduction: If many other class libraries are used in a PHP system implementation, these class libraries may be developed by different engineers, so the mapping rules between class names and the files where they are located are different. At this time, if you want to implement automatic loading of the class library, you must implement all mapping rules in the __autoload function. This will cause __autoload to be very complicated or even impossible to implement. At the same time, it will also make the __autoload function very bloated. It will have a great negative impact on future system maintenance and performance. (Disadvantages of __autoload)

spl_autoload_register:

Register the given function as an implementation of __autoload. To put it simply, the function is registered in the __autoload function stack of SPL and the system default __autload() function is removed.

<span>function</span> __autoload(<span>$className</span><span>) {  
    </span><span>echo</span> 'autload class:', <span>$className</span>, '<br />'<span>;  
}  
</span><span>function</span> classLoader(<span>$className</span><span>) {  
    </span><span>echo</span> 'SPL load class:', <span>$className</span>, '<br />'<span>;  
}  
spl_autoload_register(</span>'classLoader'<span>);  
</span><span>new</span> Test();<span>//</span><span>结果:SPL load class:Test </span>

<p><strong>Tip:</strong></p>

Function Description

<pre class="code"><span><strong><code>bool spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )
</code></strong></span>
  • autoload_function [optional] Function added to the autoload stack. The default is spl_autoload().
    • You can also call the spl_autoload_register() function to register a callback function instead of providing a string name for the function. For example, if you provide an array such as array('class','method'), you can use the method of an object .
  • throw [optional] whether to throw an exception when registration cannot be successful
  • prepend [Optional] Whether to add this function to the head of the queue instead of the tail of the queue.
<p><strong>备注:</strong>SPL自动加载功能是由spl_autoload() ,spl_autoload_register(), spl_autoload_functions() ,spl_autoload_extensions()和spl_autoload_call()函数提供的。</p>

3. Phalcon’s class automatic loading

PhalconLoader Universal Class Loader is intended to help the project automatically load classes in the project according to the protocol (This component helps to load your project classes automatically based on some conventions). Phalcon supports four class loading methods, the order of which is registering class name, registering namespace, registering prefix and registering folder.

Phalcon’s default file suffix is ​​php, of course you can also configure it yourself (setExtensions()).

1. Register class name

<?<span>php
</span><span>$loader</span> = <span>new</span><span> \Phalcon\Loader();
</span><span>$loader</span>-><span>registerClasses(
    </span><span>array</span><span>(
        </span>"Some"         => "library/OtherComponent/Other/Some.php",
        "Example\Base" => "vendor/example/adapters/Example/BaseClass.php",<span>
    )
);
</span><span>$loader</span>-><span>register();    
</span><span>//</span><span> i.e. library/OtherComponent/Other/Some.php</span>
<span>$some</span> = <span>new</span> Some();

<p>具体实现:</p>

2. Register namespace

<?<span>php
</span><span>$loader</span> = <span>new</span><span> \Phalcon\Loader();
</span><span>$loader</span>-><span>registerNamespaces(
    </span><span>array</span><span>(
       </span>"Example\Base"    => "vendor/example/base/",
       "Example\Adapter" => "vendor/example/adapter/",
       "Example"         => "vendor/example/",<span>
    )
);
</span><span>$loader</span>-><span>register();
</span><span>//</span><span> vendor/example/adapter/Some.php</span>
<span>$some</span> = <span>new</span> Example\Adapter\Some();

When using namespaces or external libraries to organize code, you can register the namespace to automatically load the libraries it contains.

对于命名空间对应的路径,要其末尾加一个斜杠。

<p>具体实现:</p>

3. Registration prefix

<?<span>php
</span><span>$loader</span> = <span>new</span><span> \Phalcon\Loader();
</span><span>$loader</span>-><span>registerPrefixes(
    </span><span>array</span><span>(
       </span>"Example_Base"     => "vendor/example/base/",
       "Example_Adapter"  => "vendor/example/adapter/",
       "Example_"         => "vendor/example/",<span>
    )
);    
</span><span>$loader</span>-><span>register();    
</span><span>//</span><span> vendor/example/adapter/Some.php</span>
<span>$some</span> = <span>new</span> Example_Adapter_Some();

Similar to namespaces, phalcon will no longer support prefixes starting from 2.1.0.

<p>具体实现:</p>

4. Register folder

<?<span>php
</span><span>$loader</span> = <span>new</span><span> \Phalcon\Loader();    
</span><span>$loader</span>-><span>registerDirs(
    </span><span>array</span><span>(
        </span>"library/MyComponent/",
        "library/OtherComponent/Other/",
        "vendor/example/adapters/",
        "vendor/example/"<span>
    )
);    
</span><span>$loader</span>-><span>register();    
</span><span>//</span><span> i.e. library/OtherComponent/Other/Some.php</span>
<span>$some</span> = <span>new</span> Some();

Can automatically load class files in the registration directory. However, this method is not recommended in terms of performance, because Phalcon will look for a large number of files with the same class name in each folder. When using the registration directory to automatically load, pay attention to the relevance of the registration directory, that is, put the important directories in front.

<p>具体实现:</p>

5. 修改当前策略(Modifying current strategies)

即为当前自动加载数据添加额外的值。

<?<span>php
</span><span>//</span><span> Adding more directories</span>
<span>$loader</span>-><span>registerDirs(
    </span><span>array</span><span>(
        </span>"../app/library/",
        "../app/plugins/"<span>
    )</span>,
    <span>true</span><span>
);</span>

 

注册时添加第二个参数值true,使其与原数组合并。

6. 安全层(Security Layer)

没有进行任何安全检查的自动加载器,如下:

<?<span>php
</span><span>//</span><span>Basic autoloader</span>
spl_autoload_register(<span>function</span>(<span>$className</span><span>) {
    </span><span>if</span> (<span>file_exists</span>(<span>$className</span> . '.php'<span>)) {
        </span><span>require</span> <span>$className</span> . '.php'<span>;
    }
});</span>

 

假如我们没有进行任何安全检查时,如果误启了自动加载器,那么恶意准备的字符串就回作为参数访问程序中的重要文件。

<?<span>php

</span><span>//</span><span>This variable is not filtered and comes from an insecure source</span>
<span>$className</span> = '../processes/important-process'<span>;

</span><span>//</span><span>Check if the class exists triggering the auto-loader</span>
<span>if</span> (<span>class_exists</span>(<span>$className</span><span>)) {
    </span><span>//</span><span>...</span>
}

 

Phalcon的做法是删除任何无用的字符串,减少被攻击的可能性。

7. 自动加载事件

在下面的例子中,而不必使用类加载器,使我们获得调试信息的流程操作:

<?<span>php
</span><span>$eventsManager</span> = <span>new</span><span> \Phalcon\Events\Manager();
</span><span>$loader</span> = <span>new</span><span> \Phalcon\Loader();
</span><span>$loader</span>->registerNamespaces(<span>array</span><span>(
       </span>'Example\\Base' => 'vendor/example/base/',
       'Example\\Adapter' => 'vendor/example/adapter/',
       'Example' => 'vendor/example/'<span>
));
</span><span>//</span><span>Listen all the loader events</span>
<span>$eventsManager</span>->attach('loader', <span>function</span>(<span>$event</span>, <span>$loader</span><span>) {
    </span><span>if</span> (<span>$event</span>-><span>getType</span>() == 'beforeCheckPath'<span>) {
        </span><span>echo</span> <span>$loader</span>-><span>getCheckedPath();
    }
});
</span><span>$loader</span>->setEventsManager(<span>$eventsManager</span><span>);
</span><span>$loader</span>->register();

 

Phalcon自动加载支持以下事件:

  • beforeCheckClass,自动加载的过程开始前触发,当返回布尔假可以停止活动操作。
  • pathFound,当一个类装入器定位触发
  • afterCheckClass,自动加载的过程完成后触发。

8. 注意事项(Troubleshooting)

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1092699.htmlTechArticlePhalcon自动加载(PHP自动加载),phalcon加载php 自动加载(phalcon\Loader) 转载请注明来源 一、php文件引入 通过 include() 或 require() 函数,可以在PH...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version