search
HomeBackend DevelopmentPHP TutorialYii学习总结之安装配置_php技巧

之前写过Yii的文章,正好假期没啥事,就结合以前的文章,Yii的官方文档,再加上最近的关于Yii的收获总结一下,写个系列~~

Yii是一个基于组件的高性能PHP框架,用于开发大型Web应用。Yii采用严格的OOP编写,并有着完善的库引用以及全面的教程。从 MVC,DAO/ActiveRecord,widgets,caching,等级式RBAC,Web服务,到主题化,I18N和L10N,Yii提供了今日Web 2.0应用开发所需要的几乎一切功能。事实上,Yii是最有效率的PHP框架之一。Yii是一个高性能的PHP5的web应用程序开发框架。通过一个简单的命令行工具 yiic 可以快速创建一个web应用程序的代码框架,开发者可以在生成的代码框架基础上添加业务逻辑,以快速完成应用程序的开发。

安装Yii

在安装Yii之前,你必须配置好你的开发环境,如一台支持PHP5.1.0以上版本的Web服务器。Yii已经在Windows和Linux操作系统上的 Apache Web服务器测试通过。它可能也会运行在其他平台上的支持PHP5的Web服务器,互联网上公布了很多免费资源,你可能会获得一个配置好PHP5的Web 服务器环境。在这里我们会抛开Web服务器和PHP5的安装。
Yii的安装其实非常简单,实际只需要两个步骤:
http://www.yiiframework.com/ 下载Yii框架 解压下载文件到Web服务器可访问的目录下。
安装完成后,建议你检查一下当前服务器是否已经满足了Yii的所有要求。
幸运的是,这样做很容易,Yii自带了一个简单的检查工具。要调用它,在你的浏览器地址栏中输入:http://yourhostname/path/to/yii/requirements/index.php,下面将显示你服务器的配置。使用检查工具,确定服务器没有安装和使用扩展或组件,但它只是给出一个建议,以确保可以确定安装。正如你看到的,下在的检查结果,并非都是 Passed(通过)状态,也有部份显示Warning(警告)。当然,你的配置情况可能会略有不同,因此,你的显示结果也会有所不同。其实下面的细节部份没有必要全部能通过。但部份也是必要的,根据 Conclusion(结论)这个段落的内容:你的服务器配置满足了Yii的最低要求。(Your server configuration satisfies the minimum requirements by Yii.)

创建一个新的应用程序
Yii的安装位置是你已经知道的
WebRoot是你的Web服务器配置的根目录
从你的命令行,进入到framework目录,并执行以下内容:

复制代码 代码如下:

  % cd Webroot/testdrive/framework
  % yiic webapp ../../testdrive
  Create a Web application under '/WebRoot/testdrive'? [Yes|No]
  Yes
         mkdir /WebRoot/testdrive
         mkdir /WebRoot/testdrive/assets
         mkdir /WebRoot/testdrive/css
         generate css/bg.gif
         generate css/form.css
         generate css/main.css

你的应用已经成功创建到了/WebRoot/demo下。这个webapp命令的作用是创建一个全新的Yii应用。它只需要指定一个参数,无论是绝对还是相对路径都会创建应用程序。它所生成的目录及文件只是应用程序的一个骨架。

复制代码 代码如下:

testdrive/
   index.php                 Web 应用入口脚本文件
   index-test.php            功能测试使用的入口脚本文件
   assets/                   包含公开的资源文件
   css/                      包含 CSS 文件
   images/                   包含图片文件
   themes/                   包含应用主题
   protected/                包含受保护的应用文件
      yiic                   yiic 命令行脚本
      yiic.bat               Windows 下的 yiic 命令行脚本
      yiic.php               yiic 命令行 PHP 脚本
      commands/              包含自定义的 'yiic' 命令
         shell/              包含自定义的 'yiic shell' 命令
      components/            包含可重用的用户组件
         Controller.php      所有控制器类的基础类
         Identity.php        用来认证的 'Identity' 类
      config/                包含配置文件
         console.php         控制台应用配置
         main.php            Web 应用配置
         test.php            功能测试使用的配置
      controllers/           包含控制器的类文件
         SiteController.php  默认控制器的类文件
      data/                  包含示例数据库
         schema.mysql.sql    示例 MySQL 数据库
         schema.sqlite.sql   示例 SQLite 数据库
         testdrive.db        示例 SQLite 数据库文件
      extensions/            包含第三方扩展
      messages/              包含翻译过的消息
      models/                包含模型的类文件
         LoginForm.php       'login' 动作的表单模型
         ContactForm.php     'contact' 动作的表单模型
      runtime/               包含临时生成的文件
      tests/                 包含测试脚本
      views/                 包含控制器的视图和布局文件
         layouts/            包含布局视图文件
            main.php         所有视图的默认布局
            column1.php      使用单列页面使用的布局
            column2.php      使用双列的页面使用的布局
         site/               包含 'site' 控制器的视图文件
            pages/           包含 "静态" 页面
               about.php     "about" 页面的视图
            contact.php      'contact' 动作的视图
            error.php        'error' 动作的视图(显示外部错误)
            index.php        'index' 动作的视图
            login.php        'login' 动作的视图
         system/             包含系统视图文件

这时不用写一行代码,我们就可以在浏览器中访问如下 URL 来看看我们第一个 Yii 应用:

http://hostname/testdrive/index.php
 
我们会看到的,这个应用包含三个页面:首页、联系页、登录页。首页展示一些关于应用和用户登录状态的信息,联系页显示一个联系表单以便用户填写并提交他们的咨询,登录页允许用户先通过认证然后访问已授权的内容。

配置

在这个应用中,不管到那个页面url中都带有index.php,如果想把它去掉,怎么办。

1. 开启apache的mod_rewrite模块,去掉LoadModule rewrite_module modules/mod_rewrite.so前的"#"符号,确保中有"AllowOverride All"。
2. 在项目中的/protected/config/main.php中添加代码:

复制代码 代码如下:

'components'=>array(
           ...
           'urlManager'=>array(
                 'urlFormat'=>'path',
                 'showScriptName'=>false,//注意false不要用引号括上
                 'rules'=>array(
                     'sites'=>'site/index',
                 ),
           ),
           ...
       ),

3.配置服务器,Yii可以在Apache和Nginx下配置

1)Apache

在Apache服务器下,Yii需要配置.htaccess文件。配置如下

复制代码 代码如下:

RewriteEngine on
# prevent httpd from serving dotfiles (.htaccess, .svn, .git, etc.)
RedirectMatch 403 /\..*$
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
RewriteRule . index.php

 2)Nginx

Yii可以使用Nginx和PHP的FPM SAPI。配置如下

复制代码 代码如下:

server {
    set $host_path "/www/mysite";
    access_log  /www/mysite/log/access.log  main;
    server_name  mysite;
    root   $host_path/htdocs;
    set $yii_bootstrap "index.php";
    charset utf-8;
    location / {
        index  index.html $yii_bootstrap;
        try_files $uri $uri/ /$yii_bootstrap?$args;
    }
    location ~ ^/(protected|framework|themes/\w+/views) {
        deny  all;
    }
    #avoid processing of calls to unexisting static files by yii
    location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
        try_files $uri =404;
    }
    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php {
        fastcgi_split_path_info  ^(.+\.php)(.*)$;
        #let yii catch the calls to unexising PHP files
        set $fsn /$yii_bootstrap;
        if (-f $document_root$fastcgi_script_name){
            set $fsn $fastcgi_script_name;
        }
        fastcgi_pass   127.0.0.1:9000;
        include fastcgi_params;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fsn;
        #PATH_INFO and PATH_TRANSLATED can be omitted, but RFC 3875 specifies them for CGI
        fastcgi_param  PATH_INFO        $fastcgi_path_info;
        fastcgi_param  PATH_TRANSLATED  $document_root$fsn;
    }
    # prevent nginx from serving dotfiles (.htaccess, .svn, .git, etc.)
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }
}

 使用如上配置,你可以在php.ini中设置cgi.fix_pathinfo=0,这样可以避免许多不必要的系统的stat()调用。

基本安装和配置就到这里~~

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'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.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

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
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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.