菜单

Yii2杂记

2016年6月2日 - Web
最近组内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’,

],

],

 

 

 

发表评论