Yiiframework Introductory Knowledge Point Summary (picture and text tutorial) _php Example

Source: Internet
Author: User
Tags current time documentation echo date generator gettext naming convention php programming yii

This article summarizes the yiiframework of the introduction of knowledge points. Share to everyone for your reference, specific as follows:

Create a YII application skeleton

The Web is a Web site root directory
YIIC Webapp/web/demo

When you create model and curd from GII, you need to be aware

1, Model generator operation

Even in the case of a table prefix, the full name of the table is included in table name, which includes the form prefix. The following figure:

2. Crud Generator operation

In the interface, model class fills in the model name. Capitalize first letter. You can also refer to the file name generated by model generator in the Proctected/models directory when model is generated. The following figure:

If you generate a curd controller for news, Newstype, Statustype, then in Model generator, enter in model class: News, Newstype, Statustype. The case is the same case as the file name created. It's not possible to write news or news.

Create Module considerations

Module IDs are generally lowercase by using the GII to create modules. In any case, the ID that is filled out here determines the configuration in the main.php configuration file. As follows:

' Modules ' =>array (
  ' admin ' =>array (//This line of admin is the module ID. The module ID that is filled in when the module is created is written in the same
    ' class ' => ' Application.modules.admin.AdminModule ', and/or the admin here is case insensitive in Windows OS , but preferably in line with the actual directory.
  ),
),

Routing

System represents the framework directory of the YII framework
Application represents the protected directory under the application created (such as D:\wwwroot\blog).
Application.modules.Admin.AdminModule
Represents the adminmodules.php file under the Admin directory under the modules directory in the application directory (for example, d:\wwwroot\blog\protected) (which actually points to the name of the file's Class)
system.db.*
Represents all files in the DB directory under the framework directory under the YII framework.

Accessrules instructions in the controller

/**
 * Specifies the access control rules.
 * This are used by the ' AccessControl ' filter.
 * @return Array access control rules/public
function accessrules ()
{return
  array (
    ' Allow ',//Allow all users to perform ' index ' and ' view ' actions '
      actions ' =>array (' index ', ' view '),// Indicates that any user can access the index, view method
      ' users ' =>array (' * '),//represents any user
    ),
    array (' Allow ',//Allow authenticated user To perform ' Create ' and ' update ' actions ' actions '
      =>array (' Create ', ' Update '),//means only authenticated users can operate the Create, Update method
      ' users ' =>array (' @ '),//representing authenticated user
    ),
    array (' Allow ',//Allow Admin user to perform ' admin ' and ' delete '
      the actions ' actions ' =>array (' admin ', ' delete '),//means that only user admin can access the admin, delete method
      ' users ' =>array (' Admin '),//indicates the specified user, here refers to the User: admin
    ),
    array (' Deny ',//Deny all users ' users '
      =>array (' * '),
    ),
  );
}

Look at the code comments above.

User:represents the user session information. For more information check Api:cwebuser
Cwebuser represents a persistent state for a Web application.
Cwebuser as an application component with ID user. As a result, access to user status can be achieved anywhere via Yii::app ()->user

Public Function BeforeSave ()
{
  if (Parent::beforesave ())
  {
    if ($this->isnewrecord)
    {
      $ THIS->PASSWORD=MD5 ($this->password);
      $this->create_user_id=yii::app ()->user->id;//At the outset, User::model ()->user->id; (Error)
      //$this- >user->id; (Error)
      $this->create_time=date (' y-m-d h:i:s ');
    }
    else
    {
      $this->update_user_id=yii::app ()->user->id;
      $this->update_time=date (' y-m-d h:i:s ');
    }
    return true;
  }
  else
  {return
    false;
  }
}

Getter method or/and setter method

<?php/** * Useridentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided * data can identity the user.
   * * Class Useridentity extends Cuseridentity {/** * authenticates a user.
   * The example implementation makes sure if the username and password * are both ' demo '. * In practical applications, this should is changed to authenticate * against some persistent user identity storage (E.
   G. Database).
   * @return Boolean whether authentication succeeds.
  * * Private $_id;
    Public function Authenticate () {$username =strtolower ($this->username);
    $user =user::model ()->find (' LOWER (username) =? ', array ($username));
    if ($user ===null) {$this->errorcode=self::error_username_invalid; } else {//if (!
        User::model ()->validatepassword ($this->password)) if (! $user->validatepassword ($this->password)) { $this->errorcode=self::error_pAssword_invalid;
        else {$this->_id= $user->id;
        $this->username= $user->username;
      $this->errorcode=self::error_none;
  } return $this->errorcode===self::error_none;
  The Public Function getId () {return $this->_id;

 }
}

model/user.php

Public Function BeforeSave ()
{
  if (Parent::beforesave ())
  {
    if ($this->isnewrecord)
    {
      $ THIS->PASSWORD=MD5 ($this->password);
      $this->create_user_id=yii::app ()->user->id;//==== mainly for this sentence. Get the ID of the login account
      $this->create_time=date (' y-m-d h:i:s ');
    }
    else
    {
      $this->update_user_id=yii::app ()->user->id;
      $this->update_time=date (' y-m-d h:i:s ');
    }
    return true;
  }
  else
  {return
    false;
  }
}

More relevant:

/*
because Ccomponent is the top-most parent class for post, add the Geturl method .... The following description:
ccomponent is the base class for all component classes.
Ccomponent implements a protocol that defines, uses attributes, and events.
properties are defined by getter methods or/and setter methods. Accessing a property is like accessing a normal object variable. The read or write property invokes the expected getter or setter method,
For example:
$a = $component->text;   Equivalent to $a = $component->gettext ();
$component->text= ' abc '; Equivalent to $component->settext (' abc ');
The getter and setter methods are formatted as follows
//getter, defines a readable property ' text ' Public
function GetText () {...}
Setter, defines a writable property ' text ' and $value to is set to the property public
function SetText ($value) { ... }
*/Public
function GetUrl ()
{return
  Yii::app ()->createurl (' Post/view ', array (
    ' id ' =>$ This->id,
    ' title ' => $this->title)
  ;
}

Rules method in the model


 /* Rules method: Specifies that the validation rule of the Model property
 when calling the Validate or Save method
 must be the property that the user entered. such as ID, author ID, etc. are set by code or database without appearing in rules.
 * */** * @return Array validation rules for model attributes.
 * * Public
function rules ()
{
  //note:you should only define the rules for those attributes that
  //would rec Eive user inputs.
  Return Array (
  ' news_title, news_content ', ' required '),
  array (' news_title ', ' length ', ' Max ' =>128) ,
  Array (' news_content ', ' length ', ' Max ' =>8000),
  Array (' Author_name, type_id, Status_id,create_time, Update_time, create_user_id, update_user_id ', ' safe '),
  //The following rule was used by search ().
  Please remove the those attributes that should is searched.
  Array (' IDs, News_title, News_content, Author_name, type_id, status_id, Create_time, Update_time, create_user_id, Update_ user_id ', ' safe ', ' on ' => ' search ')
  ;
}

Description

1, verify that the field must be a user-entered properties. Content that is not entered by the user, without authentication.
2, the Operation field in the database (even if it is generated by the system, such as the creation time, update time and other fields--in the Boylee provided by the Yii_computer source code, the system-generated properties are not in safe. See the code below). for data that is not provided by the form, you cannot write to the database as long as it is not validated in the rules method and is added to safe .

Yii_computer's news.php model about rules method

/**
 * @return Array validation rules for model attributes.
 * * Public
function rules ()
{
  //note:you should only define the rules for those attributes that
  //would recei ve user inputs.
  Return Array (
    ' news_title, news_content ', ' required '),
    array (' news_title ', ' length ', ' Max ' =>128, ') Encoding ' => ' utf-8 '),
    array (' news_content ', ' length ', ' Max ' =>8000, ' encoding ' => ' utf-8 '),
    Array ( ' Author_name ', ' length ', ' Max ' =>10, ' encoding ' => ' utf-8 '),
    array (' status_id, type_id ', ' safe '),
    // The following is used by search ().
    Please remove the those attributes that should is searched.
    Array (' IDs, News_title, News_content, Author_name, type_id, status_id ', ' safe ', ' on ' => ' search ')
  ;
}

Three ways to display dynamic content in a view

1, directly in the view file in the PHP code to achieve. such as displaying the current time, in the view:

Copy Code code as follows:
<?php echo Date ("y-m-d h:i:s");? >

2, in the controller to achieve the display content, through the render of the second parameter to the view

The Controller method contains:

$theTime =date ("y-m-d h:i:s");
$this->render (' HelloWorld ', Array (' time ' => $theTime));

View File:

Copy Code code as follows:
<?php echo $time;? >

The data for the second parameter of the called Render () method is an array (array type), and the render () method extracts the values from the array to the view script, and the key (key value) in the array will be the variable name supplied to the view script. In this example, the key value of the array is Time,value (value) is $thetime the variable name $time is extracted for use by the view script. This is a way to pass the controller's data to the view.

3, the view and the controller is very close brother, so the view file $this refers to the controller rendering this view. Modify the previous example to define a common property for a class in the controller, rather than a local variable, which is the value that is the current date and time. The properties of this class are then accessed through $this in the view.

View Naming conventions

View file name, please do the same as ActionId. But keep in mind that this is just a recommended naming convention. In fact, the view file name does not have to be the same as ActionId, simply pass the name of the file as the first argument to render ().

DB related

$PRERFP = Prerfp::model ()->findall (
  Array (
    ' limit ' => ' 5 ',
    ' order ' => ' releasetime desc '
  )
);

$model = Finishrfp::model ()->findall (
  Array (
    ' select ' => ' companyname,title,releasetime ',
    ' Order ' => ' releasetime desc ',
    ' limit ' =>)
;
foreach ($model as $val) {
  $NOTICEARR [] = "in". $val->title. " Bidding, ". $val->companyname." Winning bidder. ";
}

$model = Cgnotice::model ()->findall (
  Array (
    ' select ' => ' status,content,updatetime ',
    ' condition ') => ' status =: Status ',
    ' params ' => array (': Status ' =>0),
    ' order ' => ' updatetime desc ',
    ' limit ' = >)
);
foreach ($model as $val) {
  $NOTICEARR [] = $val->content;
}

$user =user::model ()->find (' LOWER (username) =? ', array ($username));

$noticetype = Dictionary::model ()->find (Array (
 ' condition ' => ' type ' = ' noticetype ')
);

Find the line of postid=10
$post =post::model ()->find (' postid=:p ostid ', Array (':p ostid ' =>10));

You can also use $condition to specify more complex query conditions. Without the use of strings, we can make $condition an instance of Cdbcriteria, which allows us to specify conditions that are not limited to where. For example:

$criteria =new Cdbcriteria;
$criteria->select= ' title '; Select only ' title ' column
$criteria->condition= ' postid=:p ostid ';
$criteria->params=array (':p ostid ' =>10);
$post =post::model ()->find ($criteria); $params don't need it.

Note that when using Cdbcriteria as a query condition, $params parameter is no longer needed because it can be specified in Cdbcriteria, as above.

One way to replace Cdbcriteria is to pass an array to the Find method. The keys and values of the array correspond to the attribute names and values of the standard (criterion), and the example above can be rewritten as follows:

$post =post::model ()->find (Array (
 ' select ' => ' title ',
 ' condition ' => ' postid=:p ostid '), '
 Params ' =>array (':p ostid ' =>10))
;

Other

1, Link

Copy Code code as follows:
<span class= "tt" ><?php Echo chtml::link (Controller::utf8_substr ($val->title,0,26), Array (' prerfp/ Details ', ' id ' => $val->rfpid), array (' target ' => ' _blank '));? ></a> </span>

Find API Documentation: cHTML's link () method

Copy Code code as follows:
<span class= "tt" ><a target= "_blank" title= "<?php echo $val->title;? > "href=" <?php Echo $this->createurl (' prerfp/details ', array (' ID ' => $val->rfpid));? > "><?php echo controller::utf8_substr ($val->title,0,26);?></a> </span>

Find the API documentation: Ccontroller's CreateURL () method

The above two connection effects are equivalent

Component contains

An example:

The following code is at the bottom of the view:

Copy Code code as follows:
<?php $this->widget (' Notice ');?>

Open the notice.php file under Protected/components, which reads as follows:

<?php
yii::import (' Zii.widgets.CPortlet ');
Class Banner extends Cportlet
{
  protected function rendercontent ()
  {
    $this->render (' Banner ');
  }
}

The rendered view is banner in the Protected/components/views directory.

Specific view API, keywords:cportlet

Get current host

Yii::app ()->request->getservername ();
and
$_server[' http_host '];
$url = ' http://'. Yii::app ()->request->getservername (); $url. = Ccontroller::createurl (' User/activateemail ', Array (' Emailactivationkey ' => $activationKey));
echo $url;

About adding CKEditor extensions in the event of a news release

$this->widget (' Application.extensions.editor.CKkceditor ', Array (
  "model" => $model,        # Data-model
  "attribute" => ' news_content ',     # attribute in the Data-model
  "height" => ' 300px ',
  "width" => ' 80% ',
"Filespath" =>yii::app ()->basepath. " /.. /up/","
Filesurl "=>yii::app ()->baseurl." /up/",
 );

Echo Yii::app ()->basepath

If the project directory is in: D:\wwwroot\blog directory. The value above is d:\wwwroot\blog\protected. Note that the path finally has no backslash.

Echo Yii::app ()->baseurl;

If the project directory is in: D:\wwwroot\blog directory. The value above is/blog. Note that the path finally has no backslash.

(D:\wwwroot is the site root directory), Notice the above two differences. One is BasePath, one is BaseURL

Other (not necessarily true)

In a view corresponding to a controller A, call the method in the B model, using: B::model ()->b the method name () in the model;

Some APIs that need to be mastered upfront
CHtml

I hope this article will help you with your PHP programming based on the YII framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.