YII Framework学习教程-用YIIC快速创建YII应用之三-2011-11-11


4.yiic shell

此功能是最常用的功能。他可以帮助我们创建大部分的程序结构。具体实现的内容需要我们自己来实现。

如何使用yiic shell太和其他的命令有点不同。因为他是依赖与一个web应用的。

通过如下命令进入指定web应用的shell模式

/www/yii_dev/yii/framework# php yiic shell  ../../testwebap/index.php

例如上述,进入 testwebap的命令模式,注意指定入口文件,一般是index.php

/www/yii_dev/yii/framework# php yiic shell ../../testwebap/index.php
Yii Interactive Tool v1.1 (based on Yii v1.1.8)
Please type 'help' for help. Type 'exit' to quit.
>> 

exit退出

help列出帮助信息


/*

>> help
At the prompt, you may enter a PHP statement or one of the following commands:
 - controller
 - crud
 - form
 - help
 - model
 - module

Type 'help <command-name>' for details about a command.

To expand the above command list, place your command class files
under 'protected/commands/shell', or a directory specified
by the 'YIIC_SHELL_COMMAND_PATH' environment variable. The command class
must extend from CConsoleCommand.

*/


shell模式提供了controller,crud,form,help,model,module几个命令。

了解mvc的,应该不用说了。

如果我们要查看具体命令的使用方法可以

help 命令

来进行查看。


上面说要确保'protected/commands/shell'有必要的内容,一般用yiic webapp创建的应用都有。这个是是哟给你yiic shel模式必备的。你也可以对命令进行扩展。


help module

>> help module
USAGE
  module <module-ID>

DESCRIPTION
  This command generates an application module.

PARAMETERS
 * module-ID: required, module ID. It is case-sensitive.

创建一个模块

例如

>> module testmod
      mkdir /www/yii_dev/testwebap/protected/modules
      mkdir /www/yii_dev/testwebap/protected/modules/testmod
      mkdir /www/yii_dev/testwebap/protected/modules/testmod/models
      mkdir /www/yii_dev/testwebap/protected/modules/testmod/components
      mkdir /www/yii_dev/testwebap/protected/modules/testmod/controllers
   generate controllers/DefaultController.php
      mkdir /www/yii_dev/testwebap/protected/modules/testmod/views
      mkdir /www/yii_dev/testwebap/protected/modules/testmod/views/default
   generate views/default/index.php
      mkdir /www/yii_dev/testwebap/protected/modules/testmod/views/layouts
      mkdir /www/yii_dev/testwebap/protected/modules/testmod/messages
   generate TestmodModule.php

Module 'testmod' has been created under the following folder:
    /www/yii_dev/testwebap/protected/modules/testmod

You may access it in the browser using the following URL:
    http://hostname/path/to/index.php?r=testmod

Note, the module needs to be installed first by adding 'testmod'
to the 'modules' property in the application configuration.

>> 

生成如下代码

├── models
│   ├── ContactForm.php
│   └── LoginForm.php
├── modules
│   └── testmod
│       ├── components
│       ├── controllers
│       ├── messages
│       ├── models
│       ├── TestmodModule.php
│       └── views
├── runtime
├── tests


我们生成的testwebap项目默认不是modules,controller模式的。这里需要修改配置文件才可以使用

在配置文件中修改如下

'modules'=>array('testmod',),

通过

http://www.localyii.com/testwebap/index.php?r=testmod

就可以访问了


 help controller

>>  help controller
USAGE
  controller <controller-ID> [action-ID] ...

DESCRIPTION
  This command generates a controller and views associated with
  the specified actions.

PARAMETERS
 * controller-ID: required, controller ID, e.g., 'post'.
   If the controller should be located under a subdirectory,
   please specify the controller ID as 'path/to/ControllerID',
   e.g., 'admin/user'.

   If the controller belongs to a module, please specify
   the controller ID as 'ModuleID/ControllerID' or
   'ModuleID/path/to/Controller' (assuming the controller is
   under a subdirectory of that module).

 * action-ID: optional, action ID. You may supply one or several
   action IDs. A default 'index' action will always be generated.

EXAMPLES
 * Generates the 'post' controller:
        controller post

 * Generates the 'post' controller with additional actions 'contact'
   and 'about':
        controller post contact about

 * Generates the 'post' controller which should be located under
   the 'admin' subdirectory of the base controller path:
        controller admin/post

 * Generates the 'post' controller which should belong to
   the 'admin' module:
        controller admin/post

NOTE: in the last two examples, the commands are the same, but
the generated controller file is located under different directories.
Yii is able to detect whether 'admin' refers to a module or a subdirectory.

controller  控制器名称  action名称列表

控制器名称是必须的,action名称是可以选的,也可以是多个。没有则默认有一个index

如果要为指定的应用模块创建一个控制器需要指定模块名称路径。例如

controller admin/post

位置admin模块创建post控制器类

创建test控制器,action有action1,action2,action3

>> controller test   action1 action2 action3
   generate TestController.php
      mkdir /www/yii_dev/testwebap/protected/views/test
   generate action1.php
   generate action2.php
   generate action3.php
   generate index.php

Controller 'test' has been created in the following file:
    /www/yii_dev/testwebap/protected/controllers/TestController.php

You may access it in the browser using the following URL:
    http://hostname/path/to/index.php?r=test

>> 

├── controllers
│   ├── SiteController.php
│   └── TestController.php

在项目testwebap中多了一个

TestController.php的文件

文件内容

<?php

class TestController extends Controller
{
	public function actionAction1()
	{
		$this->render('action1');
	}

	public function actionAction2()
	{
		$this->render('action2');
	}

	public function actionAction3()
	{
		$this->render('action3');
	}

	public function actionIndex()
	{
		$this->render('index');
	}

	// -----------------------------------------------------------
	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}

view下也自动为我们创建了相关页面
├── views
│   ├── layouts
│   │   ├── column1.php
│   │   ├── column2.php
│   │   ├── main.php
│   │   └── main.php~
│   ├── site
│   │   ├── contact.php
│   │   ├── error.php
│   │   ├── index.php
│   │   ├── login.php
│   │   └── pages
│   └── test
│       ├── action1.php
│       ├── action2.php
│       ├── action3.php
│       └── index.php
<?php
$this->breadcrumbs=array(
	'Test'=>array('test/index'),
	'Action1',
);?>
<h1><?php echo $this->id . '/' . $this->action->id; ?></h1>

<p>You may change the content of this page by modifying the file <tt><?php echo __FILE__; ?></tt>.</p>



具体内容就需要自己来修改了。


通过
可以访问。



以下操作需要数据库的。
配额之文件中修改如下
		/*
		'db'=>array(
			'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
		),
		*/
		// uncomment the following to use a MySQL database
		
		'db'=>array(
			'connectionString' => 'mysql:host=localhost;dbname=testdrive',
			'emulatePrepare' => true,
			'username' => 'root',
			'password' => '',
			'charset' => 'utf8',
		),

然后创建在mysql中创建
testdrive数据库
CREATE TABLE `tbl_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(128) NOT NULL,
  `password` varchar(128) NOT NULL,
  `email` varchar(128) DEFAULT NULL,
  PRIMARY KEY (`id`)
)
tbl_user数据表




help model


>> help model
USAGE
  model <class-name> [table-name]

DESCRIPTION
  This command generates a model class with the specified class name.

PARAMETERS
 * class-name: required, model class name. By default, the generated
   model class file will be placed under the directory aliased as
   'application.models'. To override this default, specify the class
   name in terms of a path alias, e.g., 'application.somewhere.ClassName'.

   If the model class belongs to a module, it should be specified
   as 'ModuleID.models.ClassName'.

   If the class name ends with '*', then a model class will be generated
   for EVERY table in the database.

   If the class name contains a regular expression deliminated by slashes,
   then a model class will be generated for those tables whose name
   matches the regular expression. If the regular expression contains
   sub-patterns, the first sub-pattern will be used to generate the model
   class name.

 * table-name: optional, the associated database table name. If not given,
   it is assumed to be the model class name.

   Note, when the class name ends with '*', this parameter will be
   ignored.

EXAMPLES
 * Generates the Post model:
        model Post

 * Generates the Post model which is associated with table 'posts':
        model Post posts

 * Generates the Post model which should belong to module 'admin':
        model admin.models.Post

 * Generates a model class for every table in the current database:
        model *

 * Same as above, but the model class files should be generated
   under 'protected/models2':
        model application.models2.*

 * Generates a model class for every table whose name is prefixed
   with 'tbl_' in the current database. The model class will not
   contain the table prefix.
        model /^tbl_(.*)$/

 * Same as above, but the model class files should be generated
   under 'protected/models2':
        model application.models2./^tbl_(.*)$/

>> 




>> model User tbl_user
   generate models/User.php
   generate fixtures/tbl_user.php
   generate unit/UserTest.php

The following model classes are successfully generated:
    User

If you have a 'db' database connection, you can test these models now with:
    $model=User::model()->find();
    print_r($model);


├── migrations
├── models
│   ├── ContactForm.php
│   ├── LoginForm.php
│   └── User.php
├── modules
│   └── testmod
│       ├── components

<?php

/**
 * This is the model class for table "tbl_user".
 *
 * The followings are the available columns in table 'tbl_user':
 * @property integer $id
 * @property string $username
 * @property string $password
 * @property string $email
 */
class User extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return User the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'tbl_user';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('username, password', 'required'),
			array('username, password, email', 'length', 'max'=>128),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, username, password, email', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'Id',
			'username' => 'Username',
			'password' => 'Password',
			'email' => 'Email',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);

		$criteria->compare('username',$this->username,true);

		$criteria->compare('password',$this->password,true);

		$criteria->compare('email',$this->email,true);

		return new CActiveDataProvider('User', array(
			'criteria'=>$criteria,
		));
	}
}





├── tests
│   ├── bootstrap.php
│   ├── fixtures
│   │   └── tbl_user.php
│   ├── functional
│   │   └── SiteTest.php
│   ├── phpunit.xml
│   ├── report
│   ├── unit
│   │   └── UserTest.php
│   └── WebTestCase.php


 


help crud

 
>> help crud
USAGE
  crud <model-class> [controller-ID] ...

DESCRIPTION
  This command generates a controller and views that accomplish
  CRUD operations for the specified data model.

PARAMETERS
 * model-class: required, the name of the data model class. This can
   also be specified as a path alias (e.g. application.models.Post).
   If the model class belongs to a module, it should be specified
   as 'ModuleID.models.ClassName'.

 * controller-ID: optional, the controller ID (e.g. 'post').
   If this is not specified, the model class name will be used
   as the controller ID. In this case, if the model belongs to
   a module, the controller will also be created under the same
   module.

   If the controller should be located under a subdirectory,
   please specify the controller ID as 'path/to/ControllerID'
   (e.g. 'admin/user').

   If the controller belongs to a module (different from the module
   that the model belongs to), please specify the controller ID
   as 'ModuleID/ControllerID' or 'ModuleID/path/to/Controller'.

EXAMPLES
 * Generates CRUD for the Post model:
        crud Post

 * Generates CRUD for the Post model which belongs to module 'admin':
        crud admin.models.Post

 * Generates CRUD for the Post model. The generated controller should
   belong to module 'admin', but not the model class:
        crud Post admin/post

>> 




>> crud User
   generate UserController.php
   generate UserTest.php
      mkdir /www/yii_dev/testwebap/protected/views/user
   generate create.php
   generate update.php
   generate index.php
   generate view.php
   generate admin.php
   generate _form.php
   generate _view.php
   generate _search.php


Crud 'user' has been successfully created. You may access it via:
http://hostname/path/to/index.php?r=user


>> 



如果添加删除数据是需要登录的。密码用户名是admin,admin



官方实例

可以使用web版本的yii






help form


>> help form
USAGE
  form <model-class> <view-name> [scenario]

DESCRIPTION
  This command generates a form view that can be used to collect inputs
  for the specified model.

PARAMETERS
 * model-class: required, model class. This can be either the name of
   the model class (e.g. 'ContactForm') or the path alias of the model
   class file (e.g. 'application.models.ContactForm'). The former can
   be used only if the class can be autoloaded.

 * view-name: required, the name of the view to be generated. This should
   be the path alias of the view script (e.g. 'application.views.site.contact').

 * scenario: optional, the name of the scenario in which the model is used
   (e.g. 'update', 'login'). This determines which model attributes the
   generated form view will be used to collect user inputs for. If this
   is not provided, the scenario will be assumed to be '' (empty string).

EXAMPLES
 * Generates the view script for the 'ContactForm' model:
        form ContactForm application.views.site.contact

>> 



为User创建form 

userformtest

>> form User application.views.user.userformtest
   generate userformtest.php
The following form view has been successfully created:
	/www/yii_dev/testwebap/protected/views/user/userformtest.php


You may use the following code in your controller action:


public function actionUser()
{
    $model=new User;


    // uncomment the following code to enable ajax-based validation
    /*
    if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
    {
        echo CActiveForm::validate($model);
        Yii::app()->end();
    }
    */


    if(isset($_POST['User']))
    {
        $model->attributes=$_POST['User'];
        if($model->validate())
        {
            // form inputs are valid, do something here
            return;
        }
    }
    $this->render('userformtest',array('model'=>$model));
}


>> 



├── data
│   ├── schema.mysql.sql
│   ├── schema.sqlite.sql
│   └── testdrive.db
├── extensions
├── messages
│   ├── config.php
│   └── zh_cn
│       ├── login_message.php
│       └── login_message.php~
├── migrations
├── models
│   ├── ContactForm.php
│   ├── LoginForm.php
│   └── User.php
├── modules
│   └── testmod
│       ├── components
│       ├── controllers
│       ├── messages
│       ├── models
│       ├── TestmodModule.php
│       └── views
├── runtime
│   └── application.log
├── tests
│   ├── bootstrap.php
│   ├── fixtures
│   │   └── tbl_user.php
│   ├── functional
│   │   ├── SiteTest.php
│   │   └── UserTest.php
│   ├── phpunit.xml
│   ├── report
│   ├── unit
│   │   └── UserTest.php
│   └── WebTestCase.php
├── views
│   ├── layouts
│   │   ├── column1.php
│   │   ├── column2.php
│   │   ├── main.php
│   │   └── main.php~
│   ├── site
│   │   ├── contact.php
│   │   ├── error.php
│   │   ├── index.php
│   │   ├── login.php
│   │   └── pages
│   ├── test
│   │   ├── action1.php
│   │   ├── action2.php
│   │   ├── action3.php
│   │   └── index.php
│   └── user
│       ├── admin.php
│       ├── create.php
│       ├── _form.php
│       ├── index.php
│       ├── _search.php
│       ├── update.php
│       ├── userformtest.php
│       ├── _view.php
│       └── view.php

<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'user-form',
	'enableAjaxValidation'=>false,
)); ?>

	<p class="note">Fields with <span class="required">*</span> are required.</p>

	<?php echo $form->errorSummary($model); ?>

	<div class="row">
		<?php echo $form->labelEx($model,'username'); ?>
		<?php echo $form->textField($model,'username'); ?>
		<?php echo $form->error($model,'username'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'password'); ?>
		<?php echo $form->textField($model,'password'); ?>
		<?php echo $form->error($model,'password'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'email'); ?>
		<?php echo $form->textField($model,'email'); ?>
		<?php echo $form->error($model,'email'); ?>
	</div>

	<div class="row buttons">
		<?php echo CHtml::submitButton('Submit'); ?>
	</div>

<?php $this->endWidget(); ?>

</div><!-- form -->



大概用法就是这样。 接下来就是详细的了解yii生成项目的结构和设计思路。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值