炬哥技术博客

搞懂一款web框架|Yii框架项目组成

炬哥 2024年03月22日 Yii 1584 0

ec0c227a-a575-4312-bcbb-38fe667c82da.jpg

Mac电脑本地使用Homebrew搭建lnmp开发环境的正确姿势~

在上一篇文章中,我们讲述了在Mac电脑本地搭建了lnmp开发环境,在本篇文章中,我们要分析一下Yii框架的项目都有哪些组成,从源码的角度来分析这个框架是如何运行的,今天这个文章是一个开头~

1:创建yii项目

在Yii的官方网站上,可以很容易的下载到Yii框架的核心代码,通过下面的代码,就可以生成一个Yii框架的项目应用,我们在Yii的同级目录下生成了一个名字叫app的项目。

// 在当前目录下,通过yiic.php创建一个名字为app的项目文件

php YiiRoot/framework/yiic.php app ./



2:项目目录

我们进入到项目目录下,在mac终端输入tree可以看到本目录下的目录文件夹,具体的目录我已经写在下面了。

|-- assets    ----------------------------js文件

|-- css          -------------------------- css文件

|-- images     --------------------------------- 图片文件

|-- index-test.php

|-- index.php ----------------------------------- 项目入口文件

|-- protected       ----------------------------- 项目核心目录

|   |-- commands    ----------------------------- 脚本目录

|   |-- components  ----------------------------- yii组件目录

|   |-- config      ----------------------------- 项目配置目录

|   |-- controllers -----------------------------  控制器目录

|   |-- data         ---------------------------- 数据资源目录

|   |-- extensions   ---------------------------- 第三方扩展目录

|   |-- lib          ----------------------------  yii框架核心文件

|   |-- messages

|   |-- migrations

|   |-- models       ------------------------------ 数据层目录

|   |-- runtime      ------------------------------ 项目运行日志

|   |-- tests        ------------------------------ 其他测试目录

|   |-- vendor

|   |-- views        ------------------------------- 视图层日志

`-- themes         ---------------------------- 主题目录


3:入口文件

在入口文件中,我把yii的核心文件放在了protected/lib下面去了,这样,我们就可以引入yii的核心文件yii.php了。

每一个项目都有一个入口文件index.php,在index.php中,引入了两个文件一个是yii.php的核心文件,一个是main.php的配置文件,引入之后通过Yii::createWebApplication创建一个应用,同时运行这个应用。

<?php
// 如果你的php版本比较高,那么需要在入口文件中增加下列两行代码,用来屏蔽一些DEPRECATED错误
error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE & ~E_DEPRECATED);
ini_set('display_errors', 'Off');
// change the following paths if necessary
$yii=dirname(__FILE__).'/protected/lib/yii/framework/yii.php';
//echo $yii;
$config=dirname(__FILE__).'/protected/config/main.php';
// remove the following lines when in production mode
//defined('YII_DEBUG') or define('YII_DEBUG',true);
// specify how many levels of call stack should be shown in each log message
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',3);
require_once($yii);
Yii::createWebApplication($config)->run();


4:配置文件

Yii框架的配置文件在/app/protected/config中的php文件,这个目录下包括了数据库配置文件,控制台应用配置文件,在实际的项目开发中,开发者也可以自己添加配置文件

/Applications/homework/app/protected/config

|-- console.php  ----- 控制台应用配置文件

|-- database.php ----- 数据库配置文件

|-- main.php     ----- 核心配置文件

`-- test.php


database.php数据库配置文件

数据库配置文件返回一个数组,数组中包含连接数据库的基本信息

<?php
// This is the database connection configuration.
return array(
/*'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',*/
// uncomment the following lines to use a MySQL database
'class' => 'CDbConnection',
'connectionString' => 'mysql:host=localhost;dbname=test',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
);


主配置文件main.php

主配置文件同样返回一个数组,数组中有多个key,不同的key对应不同的配置项。

这些配置项都有哪是什么含义?我们会在以后的文章中讲解,这里主要看一下配置项都有哪些

<?php
// uncomment the following to define a path alias
// Yii::setPathOfAlias('local','path/to/local-folder');
// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.
return array(
   'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
   'name'=>'My Web Application',
   // preloading 'log' component
   'preload'=>array('log'),
   // autoloading model and component classes
   'import'=>array(
      'application.models.*',
      'application.components.*',
   ),
   'modules'=>array(
      // uncomment the following to enable the Gii tool
      /*
      'gii'=>array(
         'class'=>'system.gii.GiiModule',
         'password'=>'Enter Your Password Here',
         // If removed, Gii defaults to localhost only. Edit carefully to taste.
         'ipFilters'=>array('127.0.0.1','::1'),
      ),
      */
   ),
   // application components
   'components'=>array(
       'urlManager' => array(
           'urlFormat' => 'path',
            //'enablePrettyUrl' => false,
            'showScriptName' => false,
            'rules' => array(
                'users' => 'users/list',
                'users/create' => 'users/create',
                'users/update' => 'users/update',
            ),
        ),
      'user'=>array(
         // enable cookie-based authentication
         'allowAutoLogin'=>true,
      ),
      // uncomment the following to enable URLs in path-format
      /*
      'urlManager'=>array(
         'urlFormat'=>'path',
         'rules'=>array(
            '<controller:\w+>/<id:\d+>'=>'<controller>/view',
            '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
            '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
         ),
      ),
      */
      // database settings are configured in database.php
      'db'=>require(dirname(__FILE__).'/database.php'),
      'errorHandler'=>array(
         // use 'site/error' action to display errors
         'errorAction'=>YII_DEBUG ? null : 'site/error',
      ),
      'log'=>array(
         'class'=>'CLogRouter',
         'routes'=>array(
            array(
               'class'=>'CFileLogRoute',
               'levels'=>'error, warning',
            ),
            // uncomment the following to show log messages on web pages
            /*
            array(
               'class'=>'CWebLogRoute',
            ),
            */
         ),
      ),
   ),
   // application-level parameters that can be accessed
   // using Yii::app()->params['paramName']
   'params'=>array(
      // this is used in contact page
      'adminEmail'=>'webmaster@example.com',
   ),
);


5:控制器层

控制器目录:

/Applications/homework/app/protected/controllers

|-- SiteController.php   --- 

`-- UsersController.php控制器类:

所有的控制器层的文件都是首字母大写,里面的类需要继承Controller类,控制器类中的动作,也就是我们经常说的方法是以action为前缀的,这个没有什么好说,这个都是yii框架自己定义的。

<?php
class SiteController extends Controller
{
    public function actions(){}
    public function actionIndex(){
        $this->render('index');    
    }
}


6:组件层

组件文件地址

/Applications/homework/app/protected/components

.

|-- Controller.php

|-- UserIdentity.php

`-- UsersComponent.php

组件类

组件类首字母大写,继承基础类CCompent

<?php
class UsersComponent extends CComponent{
    public static function getUserList(){
        $detail = Users::getOneDetail();
        $list   = Users::getList();
        return array(
           "detail" => $detail,
            "list"  => $list
        );
    }
    public static function updateUserInfo(){
        $ret = Users::updateInfo();
        return $ret;
    }
}


7:数据层

数据层用于连接数据库,实例表对象,提供基础的查询服务

/Applications/homework/app/protected/models

|-- ContactForm.php

|-- LoginForm.php

`-- Users.php

数据类

数据类需要继承CActiveRecord类,并且需要有几个基础的方法

<?php
class Users extends CActiveRecord{
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
    public function tableName()
    {
        return 'user';
    }
    public function getDbConnection()
    {
        return Yii::app()->db;
    }
    public function attributeLabels()
    {
        return array(
            'id' => 'id'
        );
    }
    public function search()
    {
    }
    public static function updateInfo(){
        $con = self::model();
        $ret = $con->updateAll(
            array("name" => "mamba3"), // column
            "id=1"
        );
        return $ret;
    }
    public static function getOneDetail(){
        $con = self::model();
        $data= $con -> find(
            array(
                'select' => array('id','name','nick_name'),
                'order' => 'id DESC',
                'condition' => 'id = 1',
            )
        );
        $list = array();
        $list[] = array(
            'id'        => $data->id,
            'name'      => $data->name,
            'nick_name' => $data->nick_name,
        );
        return $list;
    }
    public static  function getList(){
        $con = self::model();
        $data = $con -> findAll(
            array(
                'select' => array('id', 'name', 'nick_name'),
                'order' => 'id DESC'
            )
        );
        $list = array();
        foreach($data as $item){
            $list[] = array(
                'id' => $item->id,
                'name' => $item->name,
                'nick_name' => $item->nick_name,
            );
        }
        return $list;
    }
}



打赏 支付宝打赏 微信打赏

声明:本文由发布,如需转载请注明出处。

发布评论

分享到:

炬哥技术博客

欢迎炬哥微信号:4508175 (左侧二维码扫一扫)

ThinkPHP8.0 框架,对6.*版本进行无缝升级
你是第一个吃螃蟹的人
发表评论

◎欢迎参与讨论,您可以吐槽或者留言。