Table of Contents
CI框架源码阅读笔记8 控制器Controller.php,cicontroller.php
1.  _contruct()  构造函数
2.  &get_instance
本文的参考文献:
Home php教程 php手册 CI框架源码阅读笔记8 控制器Controller.php,cicontroller.php

CI框架源码阅读笔记8 控制器Controller.php,cicontroller.php

Jun 13, 2016 am 09:20 AM
controller frame Source code notes read

CI框架源码阅读笔记8 控制器Controller.php,cicontroller.php

  最近时间有些紧,源码阅读系列更新有些慢。鉴于Controller中代码比较少,本次Blog先更新该文件的源码分析。

  在经过路由分发之后,实际的应用Controller接管用户的所有请求,并负责与用户数据的交互。CI中所有的应用控制器都应该是CI_Controller的子类(除非你扩展了CI的核心,那么你的Controller父类可以是MY_Controller)。

  在应用程序控制器中,我们经常会用到这样的代码:

/* 加载配置文件 */
$this->load->config("config_app");

/* 加载model */
$this->load->model("user");

/* 加载视图 */
$this->load->view("index");

/* 获取post */
$this->input->post("data",true);

/* 获取 get */
$this->input->get("data",true);

/* 清除xss */
$this->security->xss_clean($data);

/* mark时间点 */
$this->benchmark->mark("app_start");
Copy after login

这些是如何实现的?我们接下来就简单跟踪一下。

尽管该类的结构很简单,我们还是贴出CI_Controller的类图:

1.  _contruct() 构造函数

这里CI做了一个处理,将所有的已经加载的组件加入CI_Controller(前面我们已经看到,is_loaded函数追踪所有加载的组件):

foreach (is_loaded() as $var => $class)
{
    $this->$var =& load_class($class);
}
Copy after login

看看Controller实例化时,is_loaded追踪的组件有哪些:

这就解释了为什么我们可以通过$this->input等方式来调用CI的组件。

这还不够,顺便把Loader也搞进来:

$this->load =& load_class('Loader', 'core');

$this->load->initialize();
Copy after login

现在,可以使用Loader组件来加载配置($this->load->config),加载模型($this->load->model) 和加载视图了($this->load->view)

CI_Controller可以说是一个持有多个组件的超级类,这样的方式,非常类似于设计模式中的"代理模式"。

2.  &get_instance

这里简单解释一下,CI_Controller是一个单例模式的类,通过get_instance()方法获得该类的实例。CodeIgniter.php中get_instance函数调用的即是该方法:

public static function &get_instance()
{  
    return self::$instance;
}
Copy after login

以下是关于Controller的一些Hint:

1.  CI中Controller中可以自定义目录,例如在application/controller目录中创建目录admin,并新建IndexController,则该Controller的URL访问路径是:

test.xq.com/admin/index/
Copy after login

2.  Controller中不应该承担过多的逻辑,业务逻辑应该封装到Model中.

3.  你的Controller应该按照业务区分,例如UserController处理用户相关的请求,而AppController处理应用的请求等,这不是原则,而只是一种方式。

4.  Controller类名应该以大写字母开头,文件名应该是全小写的形式。

5.  Controller中以下划线开头的方法被CI认为是私有方法,不能够被外部直接访问。

以上就是Controller的全部内容了。

最后,还是贴出CI_Controller的源码:

class CI_Controller {

    private static $instance;

    /**
     * Constructor
     */
    public function __construct()
    {
        self::$instance =& $this;
        
        foreach (is_loaded() as $var => $class)
        {
            $this->$var =& load_class($class);
        }

        $this->load =& load_class('Loader', 'core');

        $this->load->initialize();
        
        log_message('debug', "Controller Class Initialized");
    }

    public static function &get_instance()
    {
        return self::$instance;
    }
}
Copy after login

本文的参考文献:

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to evaluate the cost-effectiveness of commercial support for Java frameworks How to evaluate the cost-effectiveness of commercial support for Java frameworks Jun 05, 2024 pm 05:25 PM

Evaluating the cost/performance of commercial support for a Java framework involves the following steps: Determine the required level of assurance and service level agreement (SLA) guarantees. The experience and expertise of the research support team. Consider additional services such as upgrades, troubleshooting, and performance optimization. Weigh business support costs against risk mitigation and increased efficiency.

How does the learning curve of PHP frameworks compare to other language frameworks? How does the learning curve of PHP frameworks compare to other language frameworks? Jun 06, 2024 pm 12:41 PM

The learning curve of a PHP framework depends on language proficiency, framework complexity, documentation quality, and community support. The learning curve of PHP frameworks is higher when compared to Python frameworks and lower when compared to Ruby frameworks. Compared to Java frameworks, PHP frameworks have a moderate learning curve but a shorter time to get started.

How do the lightweight options of PHP frameworks affect application performance? How do the lightweight options of PHP frameworks affect application performance? Jun 06, 2024 am 10:53 AM

The lightweight PHP framework improves application performance through small size and low resource consumption. Its features include: small size, fast startup, low memory usage, improved response speed and throughput, and reduced resource consumption. Practical case: SlimFramework creates REST API, only 500KB, high responsiveness and high throughput

Performance comparison of Java frameworks Performance comparison of Java frameworks Jun 04, 2024 pm 03:56 PM

According to benchmarks, for small, high-performance applications, Quarkus (fast startup, low memory) or Micronaut (TechEmpower excellent) are ideal choices. SpringBoot is suitable for large, full-stack applications, but has slightly slower startup times and memory usage.

Golang framework documentation best practices Golang framework documentation best practices Jun 04, 2024 pm 05:00 PM

Writing clear and comprehensive documentation is crucial for the Golang framework. Best practices include following an established documentation style, such as Google's Go Coding Style Guide. Use a clear organizational structure, including headings, subheadings, and lists, and provide navigation. Provides comprehensive and accurate information, including getting started guides, API references, and concepts. Use code examples to illustrate concepts and usage. Keep documentation updated, track changes and document new features. Provide support and community resources such as GitHub issues and forums. Create practical examples, such as API documentation.

How to choose the best golang framework for different application scenarios How to choose the best golang framework for different application scenarios Jun 05, 2024 pm 04:05 PM

Choose the best Go framework based on application scenarios: consider application type, language features, performance requirements, and ecosystem. Common Go frameworks: Gin (Web application), Echo (Web service), Fiber (high throughput), gorm (ORM), fasthttp (speed). Practical case: building REST API (Fiber) and interacting with the database (gorm). Choose a framework: choose fasthttp for key performance, Gin/Echo for flexible web applications, and gorm for database interaction.

Java Framework Learning Roadmap: Best Practices in Different Domains Java Framework Learning Roadmap: Best Practices in Different Domains Jun 05, 2024 pm 08:53 PM

Java framework learning roadmap for different fields: Web development: SpringBoot and PlayFramework. Persistence layer: Hibernate and JPA. Server-side reactive programming: ReactorCore and SpringWebFlux. Real-time computing: ApacheStorm and ApacheSpark. Cloud Computing: AWS SDK for Java and Google Cloud Java.

What are the common misunderstandings in the learning process of Golang framework? What are the common misunderstandings in the learning process of Golang framework? Jun 05, 2024 pm 09:59 PM

There are five misunderstandings in Go framework learning: over-reliance on the framework and limited flexibility. If you don’t follow the framework conventions, the code will be difficult to maintain. Using outdated libraries can cause security and compatibility issues. Excessive use of packages obfuscates code structure. Ignoring error handling leads to unexpected behavior and crashes.

See all articles