Yii tutorial based on 慕斯网络学院课程
Make yii enviroment
- install LAMPP or XAMPP for envirement php/apache/mysql
- install composer from getcomposer.org
- user composer to install yii: basic and advanced
- use requirements.php in the yii folder to check requirements
Configure DB and folder structure
basic template
config/ -> configuration files db.php - database configuration file, web.php - yii application configuration file
runtime/ -> log files, temp files
controllers/ -> controller files
models/ -> model files
views/ -> viewer templates and viewers
web/ -> assets - js and css files, index.php entry point to the yii application robots.txt - search engine
vendor/ -> composer modules including yiisoft self
models can be either directly setup with database command or use migration files
Model
db.php - set TablePrefix
construct model class:
class Test extends ActiveRecord
{
public static function tableName()
{
return "{{%test}}" # test is the table name, actually the real table name is prefix_test
}
}
query methods:
$this->find()->one();
$this->findOne();
$this->findAll();
$this->find()->where()
Views
boolean checkbox
<div class="remember">
<input id="remember-me" type="checkbox" />
<label for="remember-me">Remember Me</label>
</div>
can be written to
<?= $form->field($model, 'rememberMe')->checkbox([
'id' => 'remember-me',
'template' => '<div class="remember">{input}<label for="remember-me">Remember Me</label></div>
])
furthermore all fields can use same template
<?php $form=ActiveForm::begin([
'fieldConfig' => [
'template' => '{input}'
]
])
disable the layout
$this->layout = false; # set public variable public $layout = false;
return $this->renderPartial(‘index’, array(‘data’=>data))
assets
asset / static files should be copied to web/assets
make own layout
base template layout with <?=$content ?> for template rendering.
$this->layout = ‘myLayout’; # public $layout = ‘myLayout’;
make a new module
use gii to create new module
for example, to make backend admin module for shopping website. and add modules in config/web.php
modules/controllers, modules/views
set default route
make the default route setting in web.php, add:
‘defaultRoute’ => ‘myControllerName’