Yii2杂记

原创 2016年06月02日 09:28:09

最近组内Web开发用到了Yii2,我也花了一个多星期的时间来稍微研究一下这个框架。本来想把一些心得写成文章,可是时间过去了

久,有些调用关系我自己现在已经模糊不清,加上长时间没有码字,要成文还需要考虑逻辑顺序、章节的排列等。为减少这些痛

苦,我干脆把以前从各个文档中抠出来的一些文字粘贴在这里,方便以后自己需要时回顾。


安装 composer
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

yii 插件
composer global require "fxp/composer-asset-plugin:~1.1.1"
composer create-project --prefer-dist yiisoft/yii2-app-advanced yii-application

/*****cd into yii-application dir*****/
./init 

yum -y install mysql-server
yum -y install httpd
yum -y remove php*
yum -y install php54w* --skip-broken


layout "main" defined in yii\base\Application.php

"user" component defined in yii\web\Application.php, pointing to class defined in yii\web\User.php

class "User" in yii\web\User.php include member "$identityClass", which is an object of class "User" in common\models\User.php, and this class do the authentication work, the former "User" class only maintains user authentication status. Define in frontend/config/main.php:'identityClass' => 'common\models\User'.

Execute "yii migrate --migrationPath=@yii/rbac/migrations"

+------------------------+
| Tables_in_yii2advanced |
+------------------------+
| auth_assignment        |
| auth_item              |
| auth_item_child        |
| auth_rule              |     
|                        |
| country                |
| migration              |
| user                   |
+------------------------+

Yii::$app = $this; in yii\base\Application.php: public function __construct($config = [])

int frontend\views\layouts\main.php:

<?= Breadcrumbs::widget([
     'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>


yii\web\Request.php: get post data via method post()


in frontend\controllers\SiteController.php
 
public function actionContact()
{
   $model = new ContactForm();
   if ($model->load(Yii::$app->request->post()) && $model->validate())
   {
   }
}

in frontend\models\ContactForm.php

public function rules()
{       
    return [
          // name, email, subject and body are required
          [['name', 'email', 'subject', 'body'], 'required'],
          // email has to be a valid email address
          ['email', 'email'],
          // verifyCode needs to be entered correctly
          ['verifyCode', 'captcha'],
      ];
}

in yii\base\Model.php:

public function validate($attributeNames = null, $clearErrors = true)
{   
   
      $scenarios = $this->scenarios();
      $scenario = $this->getScenario();
      if (!isset($scenarios[$scenario])) {
          throw new InvalidParamException("Unknown scenario: $scenario");
      }
       
      if ($attributeNames === null) {
           $attributeNames = $this->activeAttributes();
      }       
       
      foreach ($this->getActiveValidators() as $validator) {      
          $validator->validateAttributes($this, $attributeNames);
      }
}

Validattors available:

boolean: yii\validators\BooleanValidator
captcha: yii\captcha\CaptchaValidator
compare: yii\validators\CompareValidator
date: yii\validators\DateValidator
default: yii\validators\DefaultValueValidator
double: yii\validators\NumberValidator
each: yii\validators\EachValidator
email: yii\validators\EmailValidator
exist: yii\validators\ExistValidator
file: yii\validators\FileValidator
filter: yii\validators\FilterValidator
image: yii\validators\ImageValidator
in: yii\validators\RangeValidator
integer: yii\validators\NumberValidator
match: yii\validators\RegularExpressionValidator
required: yii\validators\RequiredValidator
safe: yii\validators\SafeValidator
string: yii\validators\StringValidator
trim: yii\validators\FilterValidator
unique: yii\validators\UniqueValidator
url: yii\validators\UrlValidator
ip: yii\validators\IpValidator


public function behaviors()
{
     return [
          'access' => [
              'class' => AccessControl::className(),
              'only' => ['logout', 'signup'], 
                    'rules' => [
                     [ 
                       'actions' => ['signup'],
                       'allow' => true,
                       'roles' => ['?'],
                     ],
                     [
                       'actions' => ['logout'],
                       'allow' => true,'
                       'roles' => ['@'],
                    ],
              ],
          ],


        ];
}


class AccessControl extends ActionFilter

class ActionFilter extends Behavior

class Behavior extends Object

Behaviors, also known as mixins, allow you to enhance the functionality of an existing component class without needing to change the class's inheritance. Attaching a behavior to a component "injects" the behavior's methods and properties into the component, making those methods and properties accessible as if they were defined in the component class itself. Moreover, a behavior can respond to the events triggered by the component, which allows behaviors to also customize the normal code execution of the component.

 If you look at a Yii-generated site, you’ll see that views/layouts/main.php begins with the DOCTYPE and opening HTML tag, then has the HTML HEAD and all its jazz, then starts the BODY, and finally has the footer material and the closing tags. In the middle of the body of the code, you’ll see this line:

<?php echo $content; ?>

This is a magic line as it pulls in the page-specific content. If the site you’re looking at now used Yii, the value of $content would be all the HTML that makes up this post you’re reading. For a Yii example, when the user is looking at site/login, the SiteController‘s actionLogin() method will be called. That method will render the views/site/login.php View page, pulling that file’s contents into the main layout file at that echo $content location. That’s what’s going on behind the scenes.

So here, then, is the first key concept: if you want to change the general look of your Web site, edit the layout file (views/layouts/main.php). If you were to take your HTML mockup for your site, drop in the echo $content; line at the right place, and save it as views/layout/main.php, you will have created a custom look for your Web app. That is the basic principle and it’s essentially that simple.


$config = yii\helpers\ArrayHelper::merge(
    require(__DIR__ . '/../../common/config/main.php'),
    require(__DIR__ . '/../../common/config/main-local.php'),
    require(__DIR__ . '/../config/main.php'),
    require(__DIR__ . '/../config/main-local.php')
); 


$application = new yii\web\Application($config);
$application->run();

class Application extends \yii\base\Application
{
  protected function bootstrap()
  {
       $request = $this->getRequest();
       Yii::setAlias('@webroot', dirname($request->getScriptFile()));
       Yii::setAlias('@web', $request->getBaseUrl());


       parent::bootstrap();
  }

   public function coreComponents()
   {
       return array_merge(parent::coreComponents(), [
          'request' => ['class' => 'yii\web\Request'],  
          'response' => ['class' => 'yii\web\Response'],
          'session' => ['class' => 'yii\web\Session'],
          'user' => ['class' => 'yii\web\User'],
          'errorHandler' => ['class' => 'yii\web\ErrorHandler'],
        ]);
   }
}


yii\base\Application.php:

abstract class Application extends Module
{
    /*** $config, passed from bootstrap file, new yii\web\Application($config) ***/
    public function __construct($config = [])
    {
        Yii::$app = $this;
        $this->setInstance($this);

        $this->state = self::STATE_BEGIN;
        $this->preInit($config);
        $this->registerErrorHandler($config);


        Component::__construct($config);
    }


    public function preInit(&$config)
    { 
        // merge core components with custom components
        foreach ($this->coreComponents() as $id => $component) {
            if (!isset($config['components'][$id])) {
               $config['components'][$id] = $component;
            } 
            elseif (is_array($config['components'][$id]) && !isset($config['components'][$id]['class'])) {
                $config['components'][$id]['class'] = $component['class'];
            }
        }
    }

    public function init()
    {
        $this->state = self::STATE_INIT;
        $this->bootstrap();
    }

    public function coreComponents() 
    {
        return [
           'log' => ['class' => 'yii\log\Dispatcher'],
           'view' => ['class' => 'yii\web\View'],
           'formatter' => ['class' => 'yii\i18n\Formatter'],
           'i18n' => ['class' => 'yii\i18n\I18N'],
           'mailer' => ['class' => 'yii\swiftmailer\Mailer'],
           'urlManager' => ['class' => 'yii\web\UrlManager'],
           'assetManager' => ['class' => 'yii\web\AssetManager'],
           'security' => ['class' => 'yii\base\Security'],
      ];
    }
}


class Component extends Object
{
}

class Object implements Configurable
{
     public function __construct($config = [])
     {
        if (!empty($config)) {
           Yii::configure($this, $config);
        }
        $this->init();  // call to yii\base\Application.php
     }
}

A service locator is an object that knows how to provide all sorts of services (or components) that an application might need. Within a service locator, each component exists as only a single instance, uniquely identified by an ID. You use the ID to retrieve a component from the service locator.

In Yii, a service locator is simply an instance of yii\di\ServiceLocator or a child class.

The most commonly used service locator in Yii is the application object, which can be accessed through \Yii::$app. The services it provides are called application components, such as the request, response, and urlManager components. You may configure these components, or even replace them with your own implementations, easily through functionality provided by the service locator.

yii\di\ServiceLocator.php:
class ServiceLocator extends Component

yii\base\Module.php:
class Module extends ServiceLocator

yii\yii2-debug\Module.php:
class Module extends \yii\base\Module implements BootstrapInterface

yii\base\Application.php:
abstract class Application extends Module

yii\web\Application.php:
class Application extends \yii\base\Application

http://www.cnblogs.com/CraryPrimitiveMan/

vendor/yiisoft/yii2-gii/Module.php:

public $allowedIPs = ['127.0.0.1', '::1', '192.168.0.*']; // check log to see which IP was blocked
                                                          // then add it to allowed list

/var/www/html/advanced/frontend/runtime/logs/app.log:

2015-12-16 09:20:18 [192.168.0.104][-][ts64s8bnd2159nlp2gspf6r880][warning][yii\debug\Module::checkAccess] Access to debugger is denied due to IP address restriction. The requesting IP address is 192.168.0.104

First way(Official way): 

In your main.php config file add these two parameters in your log section and you can see log messages at the end of your page or FireBug Console in your browser. do not forget to set necessary parameters in db section.

'components' => array(
    'db'=>array(
        'enableProfiling'=>true,
        'enableParamLogging' => true,
    ),
    'log'=>array(
        'class'=>'CLogRouter',
        'routes'=>array(
                array(
                    'class'=>'CWebLogRoute',
                    'showInFireBug' => true,
                ),
                array(
                    'class'=>'CProfileLogRoute',
                    'levels'=>'profile',
                    'enabled'=>true,
                ),
        ),
    ),
);


Second way: 

In your code just change the spelling of one of your columns to something incorrect and you will get an error message contains full SQL query in your error page(you should be in YII_DEBUG mode true). something like this: 
(I have changed t.date to t.wrong_date, when you refresh your page, you will see the generated SQL which was executed in your database)


$criteria = new CDbCriteria();
            $criteria->condition = 't.wrong_date BETWEEN "'.$from_date.'"  AND "'.$to_date.'"';
            $criteria->with = array('order');
            $orders = ProductOrder::model()->findAll($criteria);


in the both ways, have YII_DEBUG true in index.php

defined('YII_DEBUG') or define('YII_DEBUG',true);

* Remember transferring to production environment, disabling gii for security sake


Inorder to successfully create RBAC tables, one has to add DbManager to "/var/www/html/yii-application/console/config/main.php"  and "/var/www/html/yii-application/frontend/config/main.php":

 'components' => [
        'log' => [
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],


      'authManager' => [
            'class' => 'yii\rbac\DbManager',
         ],
    ],


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

yii2 strace 追踪,本地文件

13631 16:16:13 execve("/usr/local/php/bin/php", ["/usr/local/php/bin/php", "/www/web/develop/erp2/ba...

yii cli模式 杂记

今天趴一下yii的cli模式,发现网上的套路不适用,修改了一下后能正常运行,写下来记忆一下。

【java】杂记2

1.Arrays.asList() 将一个数组转化为一个List对象,这个方法会返回一个ArrayList类型的对象, 这个ArrayList类并非java.util.ArrayList类,而是Ar...

QT5.3 杂记 Qt5下,QWidget系列从QtGui中被剥离出去,成为单独的QtWidget模块。随着Qt Quick2的引入,QtDeclarative也逐渐和QWidget系列也脱离关系。

摘自:http://www.cnblogs.com/aoldman/p/3968280.html   Qt5下,QWidget系列从QtGui中被剥离出去,成为单独的QtWidget模块。随着Qt...
  • fsx92
  • fsx92
  • 2015-05-31 17:35
  • 1590

杂记 (2) —— linux and C

问题 自动获取IP的网卡设置怎嘛查看IPv4? 将/etc/sysconfig/network-scripts/ifcfg-eth0中的BOOTPROTO的值更改成dhcp. 然后ifdown 网卡...

hadoop杂记-为什么会有Map-reduce v2 (Yarn)

Why Yarn: Map-reduce老矣,尚能饭否? 第一次看到Yarn的问题,就需要问问,为什么要重新设计之前这样一个成熟的架构。 “The Apache Hadoop M...

驱动杂记2:分层驱动,IRP ,I/O堆栈初步印象

分层驱动是指两个或者两个以上的驱动程序,他们分别创建设备对象,并且形成一个由高到低的 设备对象栈。IRP请求一般会被传送到设备栈的最顶层设备对象,顶层设备对象可以选择直接结束IRP 请求,也可以选...

Android开发之杂记(2)

1,Android FrameLayout的android:foreground属性可以设置单击时的前景色 <FrameLayout android:id="@+id/pos...

hadoop杂记-为什么会有Map-reduce v2 (Yarn)

前言: 现在准备计划写一个新的专题,叫做《Hadoop杂记》,里面的文章有深有浅,文章不是按入门-中级-高级的顺序组织的,如果想看看从入门到深入的书,比较推荐《the definitive guid...

2. python入门杂记

元祖 创建一个元祖(逗号是关键) touple1 = (1,2,3,4,5) //不可修改 可以使用类似列表的访问方法, 分片 touple1[1] touple1[:3]touple2 = 2...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)