PHP框架 之YII2框架 (yii2 framework – Yii PHP Framework)

PHP框架 之YII2框架 (yii2 framework – Yii PHP Framework)yii2framewor YiiPHPFramew 框架 是一个高性能 基于组件的 PHP 框架 用于快速开发现代 Web 应用程序 特别适合开发大型应用 如门户网站 社区 内容管理系统 CMS 电子商务项目和 RESTfulWeb 服务 yii2

大家好,欢迎来到IT知识分享网。

     又有新项目要撘框架,毫无意外的,我又被借调走了,又写一篇文章记录一下,这次讲的是:yii2 framework - Yii PHP Framework框架,有需要的同学自取,Yii 是一个高性能,基于组件的 PHP 框架,用于快速开发现代 Web 应用程序,特别适合开发大型应用,如门户网站、社区、内容管理系统(CMS)、电子商务项目和 RESTful Web 服务

1.安转:

1.1Composer 安装:

(需要切换国内镜像:composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/,科学上网的同学可以忽略这一步) 命令安装 Composer asset plugin,它是通过 Composer 管理 bower 和 npm 包所必须的,此命令全局生效,一劳永逸。  composer global require “fxp/composer-asset-plugin:~1.0.0”

1.1.1 基础版本

(basic作为指定目录:比如你本机的E:\phpstudy\PHPTutorial\WWW\myproject\yii)。 composer create-project –prefer-dist yiisoft/yii2-app-basic E:\phpstudy\PHPTutorial\WWW\myproject\yii  2.0.22

1.1.2 基础开发版本

composer create-project –prefer-dist –stability=dev yiisoft/yii-app-basic E:\phpstudy\PHPTutorial\WWW\myproject\yii  2.0.22

1.1.3完整版本(basic作为指定目录:比如你本机的E:/yii)

composer create-project –prefer-dist yiisoft/yii2 E:\phpstudy\PHPTutorial\WWW\myproject\yii 2.0.22

1.2官网下载安装(此种方式安装PHP版本必须大于8.1):

https://www.yiiframework.com/download

2.配置秘钥:

文件路径:yii\config\web.php  

需要配置项:cookieValidationKey

3.目录结构:

4.nginx配置:

server {         charset utf-8;         client_max_body_size 128M;         listen 80; listen for ipv4         #listen [::]:80 default_server ipv6only=on; listen for ipv6         server_name frontend.test;         root        /path/to/yii-application/frontend/web/; # 你的项目路径         index       index.php;         access_log  /path/to/yii-application/log/frontend-access.log; # nginx日志存放在项目目录下         error_log   /path/to/yii-application/log/frontend-error.log;         location / {                 try_files $uri $uri/ /index.php$is_args$args;         }         location ~ ^/assets/.*\.php$ {                 deny all;         }         location ~ \.php$ {                 include fastcgi_params;                 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;                 fastcgi_pass 127.0.0.1:9000;                 try_files $uri =404;         }              location ~* /\. {                 deny all;         } }       server {         charset utf-8;         client_max_body_size 128M;              listen 80; listen for ipv4                      server_name backend.test;         root        /path/to/yii-application/backend/web/; # 你的项目路径         index       index.php;              access_log  /path/to/yii-application/log/backend-access.log;         error_log   /path/to/yii-application/log/backend-error.log;              location / {                 try_files $uri $uri/ /index.php$is_args$args;         }              location ~ ^/assets/.*\.php$ {                 deny all;         }         location ~ \.php$ {                 include fastcgi_params;                 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;                 fastcgi_pass 127.0.0.1:9000;                  try_files $uri =404;         }              location ~* /\. {                 deny all;             } }

5.apach配置:

<VirtualHost *:80>         DocumentRoot "E:\phpstudy\PHPTutorial\WWW\myproject\yii"         ServerName www.yi.com         ServerAlias          <Directory "E:\phpstudy\PHPTutorial\WWW\myproject\yii">                 Options FollowSymLinks ExecCGI                 AllowOverride All                 Order allow,deny                 Allow from all                 Require all granted         </Directory> </VirtualHost>

5.路由:

路由美化(yii\config\web.php)
打开前路由:http://www.yi.com/web/index.php?Site/index
打开后路由:http://www.yi.com/web/site/index

//设置规则
‘urlManager’ => [
        ‘enablePrettyUrl’ => true, //是否启用 URL 美化(路径友好化).
        ‘showScriptName’ => false, //是否或略脚本名index.php 
        ‘rules’ => [
        ],
],





7.控制器(Controller):

//行为控制器 public function behaviors() {         return [             'access' => [                     'class' => \yii\filters\AccessControl::className(),                     'only' => $this->actions, // 针对哪些方法有效,默认所有                     'except' => $this->except, // 针对哪些方法不进行控制                     'rules' => [                             [                                     'allow' => false,                                     'actions' => empty($this->mustlogin) ? [] : $this->mustlogin,                                     'roles' => ['?'] // 未登录用户默认均不可访问                             ],                             [                    'allow' => true,                    'actions' => empty($this->mustlogin) ? [] : $this->mustlogin,                              'roles' => ['@'] // 登陆用户默认均可访问               ]           ]       ],       'verbs' => [            'class' => \yii\filters\VerbFilter::className(),            'actions' => $this->verbs, // 针对某些方法限制其访问方式       ]     ]; }
<?php namespace app\controllers; use app\models\User; use Yii; use yii\web\Controller; use app\models\Users; Class UsersController extends Controller{     //初始化     public function __construct($id, $module, $config = [])     {         parent::__construct($id, $module, $config);     }     //测试(访问地址:http://www.yi.com/web/index.php?r=users/index&id=1)     public static function actionIndex(){         $uid = Yii::$app->request->get('uid', '1');         $userid = Users::getdatone($uid);         var_dump($userid);die;     }     //sum,max,min,average 测试     public function actionData_test(){         //加法         $data_sum = Users::find()->sum('age');         var_dump($data_sum);         echo '<br>------<br/>';         //最大值         $data_max = Users::find()->max('age');         var_dump($data_max);         echo '<br>------<br/>';         //最小值         $data_min = Users::find()->min('age');         var_dump($data_min);         echo '<br>------<br/>';         //平均值         $data_average = Users::find()->average('age');         var_dump($data_average);         echo '<br>------<br/>';     }          //一对一(访问地址:http://www.yi.com/web/index.php?r=users/actionGetextendone&id=3)     public static function actionGetextendone(){         $id = Yii::$app->request->get("id",1);         $customer =  Users::findone($id);         $phone = $customer->getUserextendone()->asArray()->one();         var_dump($phone);die;     }     //一对多(访问地址:http://www.yi.com/web/index.php?r=users/getextendmore&id=3)     public static function actionGetextendmore(){         $id = Yii::$app->request->get("id",1);         $customer =  Users::findone($id);         $phone = $customer->getUserextendmore()->asArray()->all();         var_dump($phone);die;     } } ?>

 

8.模型(Model):

绑定数据表(GOlang实现绑定数据表和验证规则 是通过接口interface一起实现的) public static function tableName() {         return '{ 
  {%数据表名}}'; } 验证规则(GOlang实现绑定数据表和验证规则 是通过接口interface一起实现的) public function rules() {         return [                 [['encode_id', 'title', 'status', 'creater_id'], 'required'],                 [['type', 'sort'], 'filter', 'filter' => 'intval'], //此规则必须,否则就算模型里该字段没有修改,也会出现在脏属性里                 [['encode_id'], 'string', 'max' => 50],                 [['title', 'remark'], 'string', 'max' => 250],                 [['encode_id'], 'unique'],                 [['created_at', 'updated_at'], 'safe'],         ]; } 字段字典(相当于备注) public function attributeLabels() {         return [                 'id' => 'ID',                 'encode_id' => '加密id',                 'title' => '项目名称',                 'remark' => '项目描述',                 'sort' => '项目排序',                 'status' => '项目状态',                 'type' => '项目类型',                 'creater_id' => '创建者id',                 'updater_id' => '更新者id',                 'created_at' => '创建时间',                 'updated_at' => '更新时间',         ]; }
<?php namespace app\models; use yii\db\ActiveRecord; class Users extends ActiveRecord {     //初始化表名     public static function tableName()     {         return '{ 
  {%users}}';     }     //查询方法     public static function getdatone($uid=1){         return self::find()->where("id= {$uid}")->exists();     }     //一对一     public function getUserextendone()     {         return $this->hasOne(Userextend::className(), ['user_id' => 'id']);     }     //一对多     public function getUserextendmore()     {         return $this->hasMany(Userextend::className(), ['user_id' => 'id']);     } } ?>

8.视图(Views):

要显示纯文本,先调用 yii\helpers\Html::encode() 进行转码(防止注入和跨站脚本)

替代语法(里面的条件、循环和TP和CI框架一致):<?php ?>

例如(渲染一个名称为"view"的视图并使用布局 ): namespace app\controllers;  use Yii; use app\models\Post;  use yii\web\Controller;  use yii\web\NotFoundHttpException;  class PostController extends Controller{      public function actionView($id) {          $model = Post::findOne($id);          if ($model === null) {                  throw new NotFoundHttpException; //错误抛出         }         return $this->render('view', [ 'model' => $model, ]);      }  }

9.数据库:

sum()     // 返回指定列的总数。

indexBy() // 根据索引的列的名称查询结果。

10.关联模型:

ActiveRecord::hasOne()  //一对一模型    返回对应关系的单条记录

ActiveRecord::hasMany() //一对多模型    返回对应关系的多条记录

        到这里,框架的基础知识就讲得差不多了,其他的就是舔砖加瓦的工作了,大家自行补全

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/120205.html

(0)
上一篇 2025-10-31 11:00
下一篇 2025-10-31 11:15

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信