search
HomeBackend DevelopmentPHP TutorialCI框架学习笔记(二) -入口文件index.php_PHP

  上一节(CI框架学习笔记(一) - 环境安装、基本术语和框架流程)中,我们提到了CI框架的基本流程,这里再次贴出流程图,以备参考:


  作为CI框架的入口文件,源码阅读,自然由此开始。在源码阅读的过程中,我们并不会逐行进行解释,而只解释核心的功能和实现。

1. 设置应用程序环境

define('ENVIRONMENT', 'development');

这里的development可以是任何你喜欢的环境名称(比如dev,再如test),相对应的,你要在下面的switch case代码块中,对设定的环境做相关的错误控制,否则,CI框架会认为你没有配置好相应的环境,从而退出进程并给出对应的错误信息:

default:   exit('The application environment is not set correctly.');

为什么一开始就要配置ENVIRONMENT?这是因为,CI框架中很多组件都依赖于ENVIRONMENT的配置,我们看一下system中,引用ENVIRONMENT的地方:


  可以看到,很多组件都依赖于ENVIRONMENT.例如,查看system/config/Common.php, 这其中有一段引入配置文件的代码,是这样实现的:

if ( ! defined('ENVIRONMENT') OR ! file_exists($file_path = APPPATH.'config/'.ENVIRONMENT.'/config.php'))
{
  $file_path = APPPATH.'config/config.php';
}

  在CI框架中,很多配置文件都是通过这种方式引入的,因此ENVRIONMENT对于CI框架的正确运行时必须的,所以需要在开始的时候配置好ENVIRONMENT。设置ENVIRONMENT的一个好处是:可以很方便的切换系统的配置而不必修改系统代码。例如,在系统进入测试阶段时,database配置为测试的数据库,而在系统测试完毕时,database切换到线上的数据库。这好比是用一个开关控制了系统的环境切换,自然是非常方便的。

2.  配置系统目录和应用程序目录

  CI框架允许你将系统核心源码和应用程序代码分开放置,但是你必须设定好系统的system文件夹和application文件夹(同样,文件夹名字可以是任何合法的文件夹名称,而不一定使用'system'和'application'):

$system_path = 'system';
$application_folder = 'application';

接下来,有这么一段代码:

if (defined('STDIN'))
{
   chdir(dirname(__FILE__));
}

  这段代码是干嘛的呢?首先,STDIN、STDOUT、STDERR是PHP以 CLI(Command Line Interface)模式运行而定义的三个常量,这三个常量类似于Shell的stdin,stdout,stdout,分别是PHP CLI模式下的标准输入、标准输出和标准错误流。也就是说,这三行代码是为了保证命令行模式下,CI框架可以正常运行。关于PHP CLI的更多细节可以参考:http://www.php-cli.com/

3. system目录的正确性验证和application目录验证

(1). system目录的正确性验证
  Realpath返回的是目录或文件的绝对目录名(没有最后的/)

if (realpath($system_path) !== FALSE)
{
  $system_path = realpath($system_path).'/';
}
$system_path = rtrim($system_path, '/').'/';
if ( ! is_dir($system_path))
{ 
  exit("xxxxxxxx");
}

几个定义的常量(PATH结尾的常量表示目录路径,DIR结尾的变量表示目录名):
a. SELF(这里指index.php文件)
b. EXT(deprecated,废弃的,不必关注)
c. BASEPATH(system文件夹的路径)
d. FCPATH(前端控制器的路径)
e. SYSDIR(系统system目录名)
f. APPPATH(应用程序路径)
查看所有定义的常量的方法:

Print_r(get_defined_constants());

(2)application的目录验证。

代码较简单,不做过多的解释:

if (is_dir($application_folder))
{
  define('APPPATH', $application_folder.'/');
}
else
{
  if ( ! is_dir(BASEPATH.$application_folder.'/'))
  {
    exit("Your application folder path does not appear to be set correctly. Please open the following file and correct this: ".SELF);
  }

  define('APPPATH', BASEPATH.$application_folder.'/');
}

  入口文件的最后一行,引入CodeIgniter.php(也是下一步阅读的关键)。CodeIgniter.php被称为bootstrap file,也就是它是一个引导文件,是CI框架执行流程的核心文件。

require_once BASEPATH.'core/CodeIgniter.php';

  总结一下,index.php并没有做太多复杂的工作,而是类似一个后勤,为CI框架的运行提供了一系列配置参数和正确性验证,而这些配置和验证,是CI框架能够正常运行的关键。

  最后,按照惯例,贴一下整个文件的源码(简化注释版):

<?php

define('ENVIRONMENT', 'development');

if (defined('ENVIRONMENT'))
{
  switch (ENVIRONMENT)
  {
    case 'development':
      error_reporting(E_ALL);
    break;
  
    case 'testing':
    case 'production':
      error_reporting(0);
    break;

    default:
      exit('The application environment is not set correctly.');
  }
}

/*
 * SYSTEM FOLDER NAME
 */
$system_path = 'system';

/*
 * APPLICATION FOLDER NAME
 */
$application_folder = 'application';

/*
 * Resolve the system path for increased reliability
 */
if (defined('STDIN'))
{
  chdir(dirname(__FILE__));
}

if (realpath($system_path) !== FALSE)
{
  $system_path = realpath($system_path).'/';
}

$system_path = rtrim($system_path, '/').'/';

if ( ! is_dir($system_path))
{
  exit("xxxxxxxx");
}

/*
 * set the main path constants
 */
// The name of THIS file
define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));

// this global constant is deprecataaed.
define('EXT', '.php');

// Path to the system folder
define('BASEPATH', str_replace("\\", "/", $system_path));

// Path to the front controller (this file)
define('FCPATH', str_replace(SELF, '', __FILE__));

// Name of the "system folder"
define('SYSDIR', trim(strrchr(trim(BASEPATH, '/'), '/'), '/'));

// The path to the "application" folder
if (is_dir($application_folder))
{
  define('APPPATH', $application_folder.'/');
}
else
{
  if ( ! is_dir(BASEPATH.$application_folder.'/'))
  {
    exit("Your application folder path does not appear to be set correctly. Please open the following file and correct this: ".SELF);
  }

  define('APPPATH', BASEPATH.$application_folder.'/');
}

require_once BASEPATH.'core/CodeIgniter.php';

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: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

Debunking the Myths: Is PHP Really a Dead Language?Debunking the Myths: Is PHP Really a Dead Language?Apr 16, 2025 am 12:15 AM

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

The PHP vs. Python Debate: Which is Better?The PHP vs. Python Debate: Which is Better?Apr 16, 2025 am 12:03 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor