search
HomeBackend DevelopmentPHP TutorialCI framework source code reading notes 1, ci framework source code notes_PHP tutorial

CI framework source code reading notes 1, ci framework source code notes

When I first started using the CI framework, I planned to write a series of notes on CI source code reading, but unfortunately it ended in an anticlimactic manner. , there has been no action. There have been few projects recently, so I finally have some time to write something. So I prepared to record some of my previous notes and experiences, on the one hand as a memo, and on the other hand, I always reminded myself: the only way out is to learn from others, and forgetting the past means betrayal!

Basic terminology explanation

 Before starting this article, it is necessary to make a brief explanation of the terms that appear repeatedly in the article. If you are already familiar with this part, you can completely skip it. Terms that appear and are mentioned repeatedly in this article include:

Front Controller:

A component used to centrally control all user requests and send user requests to specific application controllers. In the CI framework, this refers to the CodeIgniter class. The front-end controller itself is a design pattern. For details, please refer to "J2EE Design Patterns".

Application Controller

The application controller is a specific controller that processes user request URLs. A group of related processes or requests are usually placed in an application controller. For example: UserController may contain user registration, verification, personal information, Personal page and other related operations.

MVC

 A common term is a code layering and organization model. Divide the code into M (Model, business logic), V (view, view), C (Controller, controller) and other levels to facilitate the separation of the business logic part and the view rendering part and reduce the coupling of the code. Currently, many frameworks in PHP are based on the MVC pattern, such as ZF, YII, CI, etc.

RouteRoute

Although it is called Route, it is not a router, but refers to the process of intercepting the user's request and forwarding the request to a specific Controller for processing. Different frameworks have different routing, but the basic principles are the same.

HookHook

The original Hook refers to "a link in message delivery, used to monitor the delivery of messages and add specific processing before message processing." Hook here refers to adding or changing the core functions of the system without changing the core source code of the framework. The most typical situations include: running a specific script before the controller is loaded or after the loading is completed.

CI framework configuration

The basic environment of this article: Linux x86_64 GNU/Linux. PHP(CGI)+Nginx+Mysql+redis is installed (so many server-related configurations in this article are based on Nginx, and the Apache server is temporarily ignored. ).

First download the source code of the CI framework. The download address is: http://codeigniter.org.cn/downloads. The current stable version is 2.2.0. Unzip the source code to a folder (assumed to be the /usr/nginx/html/CI directory).

Before configuring the CI framework, first browse the directory structure of the framework:

Among them:

Application : The directory of the application. All your application code should be located in this directory

index.php : The entry file of the framework

static : The directory we created ourselves to place some static files such as CSS, image and js (this can be placed in the application directory, depending on personal preference)

system : The system file of the CI framework is also the main part of source code reading

user_guide : User guide, similar to an offline user manual.

The CI framework requires less configuration:

1. Configure routes

The default application controller and 404 page are configured in Routes.php. Open the application/config/routes.php file and configure it as follows:

<span>$route</span>['default_controller'] = "index"<span>;
</span><span>$route</span>['404_override'] = '';

2. Configuration database database.php

If your application needs to provide dynamic content, then a database is almost an essential configuration. Open the application/config/database.php file. The content of the file is as follows:

The CI framework supports multi-data stream connections, default is the current default connection, and active_record is used to specify whether to enable ARM (Active Record Model). Each configuration item is very concise and will not be introduced in detail here.

3. Remove index.php

Now access your application, the url should look like this:

<span>test.xq.com/index.php/index
test.xq.com/index.php/welcome</span>

注意每个请求都会带有index.php段。去掉index.php会让URI更加美观。

打开刚刚添加的test.xq.com.conf文件,在server中添加如下配置:

<span>if ($request_filename !~* /(favicon.ico|static|uploads|js|javascript|css|images|robots\.txt|index\.php|index\.html))
{
     rewrite ^/(.*)$ /index.php?$</span>1 last<span>;
</span>}

重启服务器后,现在,URL的访问方式变成了:

<span>test.xq.com/index
test.xq.com/welcome</span>

 是不是简洁多了 :D

4.  添加.html访问后缀

  可能还有人喜欢url中添加特定的后缀,例如.html后缀使你的应用程序更类似于一系列静态文件。配置方法是,在application/config/config.php中,更改如下配置为:

<span>$config</span>['url_suffix'] = '.html';

CI框架的更多配置可以参考:

配置Vhost

  为了方便访问(相比ip地址访问的方式,域名访问有更好的可记忆性),我们可以配置vhost,配置方式为:进入nginx的vhost目录,新建配置文件(本文中为test.xq.com.conf,一般情况下,我们的每个vhost都会以域名命名)。在配置文件中输入如下内容:

<span>server {
    listen       </span>80<span>;
</span>    server_name  test.xq.com<span>;
</span>    root         /usr/nginx/html/CI/<span>;
</span><span>
    access_log logs/xq_access_log main</span><span>;
</span>    error_log  logs/testsq.log error<span>;
</span>    charset GBK<span>;
</span>    index index.php<span>;
</span><span>
    location ~ .*\.(php|php5)?$
    {
        include        fastcgi_params</span><span>;
</span>        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name<span>;
</span>        fastcgi_pass   127.0.0.1:9000<span>;
</span><span>    }

}</span>

Server中暂时没有其他rewrite配置,稍后在配置CI框架的时候,我们可以添加更多的配置类支持CI的友好URL.

打开本地的host文件,在host中添加条目:

10.130.130.130  test.xq.com   

其中10.130.130.130应该是你的服务器的IP地址。

现在,在浏览器中可以通过域名访问CI框架了。

框架流程

         在结束本文之前,我们再看看CI框架的基本流程,这个流程将贯穿源码阅读的始终,所以,很有必要认真研读一下。引用CI框架用户手册的上的流程图:

 

基本的执行流程如下:

下一步开始,将开始CI的源码阅读之旅。

 

谁可以解释下这段php代码ci框架的

这是类里面的一个方法
功能是:浏览器使用post请求发送 shop_id到服务器,这个 shop_id 就是数据库中的manufacture_id,根据这个shop_id查询数据库,把查到的记录以json格式字符串的形式输出到浏览器
 

php CI框架里遇到的问题

提示Fatal error: Class 'Test_model' not found in D:\wamp\www\CodeIgniter_2.1.2\system\core\Loader.php on line 303
意思提示这个Test_model类找不到
你的类名写错了,当然找不到了
以下为model代码,文件名为test_model.php: (类名要与文件名保持一致才行)

class Test_m extends CI_Model{ // 最好要大写都大写改成test_model
以下为contraller代码,文件名为user.php
$this->load->model('test_model'); 它加载的时候找不到class test_model

这样就应该能成功
 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/899962.htmlTechArticleCI框架源码阅读笔记1,ci框架源码笔记 最开始使用CI框架的时候,就打算写一个CI源码阅读的笔记系列,可惜虎头蛇尾,一直没有行动。最近...
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use