YiFramework 입문 지식 포인트 총화(그림 교정)
Yii 응용 골격 만 들 기
웹 사이트 루트 디 렉 터 리
yiic webapp /web/demo
GII 를 통 해 model 과 CURD 를 만 들 때 주의해 야 합 니 다.
1.모델 생 성기 조작
표 접두사 가 있 는 경우 에 도 Table Name 에는 표 접두사 가 포 함 된 표 의 전체 이름 을 입력 해 야 합 니 다.다음 그림:
2.Crud Generator 조작
이 인터페이스 에는 모델 클래스 에 모델 이름 을 입력 합 니 다.이니셜 대문자.model 을 생 성 할 때 proctected/models 디 렉 터 리 에서 model generator 를 통 해 생 성 된 파일 이름 도 참조 할 수 있 습 니 다.다음 그림:
뉴스,뉴스 타 입,statustype 세 표 에 CURD 컨트롤 러 를 생 성 하면 Model Generator 에 Model Class 에 뉴스,뉴스 타 입,Status Type 을 입력 합 니 다.대소 문 자 는 만 든 파일 이름 의 대소 문자 와 같 습 니 다.뉴스 나 NEWS 등 으로 쓰 면 안 됩 니 다.
모듈 생 성 주의사항
GII 를 통 해 모듈 을 만 들 고,Module ID 는 보통 소문 자로 만 듭 니 다.어쨌든 여기에 기 재 된 ID 는 main.php 프로필 의 설정 을 결정 합 니 다.다음 과 같다.
'modules'=>array(
'admin'=>array(// admin Module ID。 Module Module ID
'class'=>'application.modules.admin.AdminModule',// admin windows os , 。
),
),
경로시스템 은 yii 프레임 워 크 의 framework 디 렉 터 리 를 표시 합 니 다.
application 은 만 든 응용 프로그램(예 를 들 어 d:\wwroot\blog)의 proctected 디 렉 터 리 를 표시 합 니 다.
application.modules.Admin.AdminModule
응용 프로그램 디 렉 터 리(예:d:\www wroot\\blog\proctected)디 렉 터 리 에 있 는 modules 디 렉 터 리 에 있 는 Admin Modules.php 파일(실제 이 파일 의 클래스 이름 을 가리 키 는 것)을 표시 합 니 다.
system.db.*
YII 프레임 워 크 의 framework 디 렉 터 리 에 있 는 db 디 렉 터 리 에 있 는 모든 파일 을 표시 합 니 다.
컨트롤 러 의 accessRules 설명
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),// index、view
'users'=>array('*'),//
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),// create、update
'users'=>array('@'),//
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),// admin admin、delete
'users'=>array('admin'),// , :admin
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
이상 코드 주석 을 보십시오.user:사용자 세 션 정 보 를 나 타 냅 니 다.자세 한 내용 은 API:CWebUser 를 참조 하 십시오.
CWebUser 는 웹 프로그램의 지속 적 인 상 태 를 대표 합 니 다.
CWebUser 는 ID 가 user 인 응용 프로그램 구성 요소 입 니 다.따라서 어디서 든 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;// ,User::model()->user->id;( )
//$this->user->id;( )
$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 방법 또는/setter 방법
<?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 be 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;
}
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;//==== 。 ID
$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;
}
}
더 많은 관련:
/*
CComponent post , getUrl 。。。。 :
CComponent 。
CComponent 、 。
getter / setter 。 。 getter setter
:
$a=$component->text; // equivalent to $a=$component->getText();
$component->text='abc'; // equivalent to $component->setText('abc');
getter setter
// getter, defines a readable property 'text'
public function getText() { ... }
// setter, defines a writable property 'text' with $value to be 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 방법
/*
* rules :
* validate save
* 。 id, id rules 。
*/
/**
* @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('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 is used by search().
// Please remove those attributes that should not be searched.
array('id, news_title, news_content, author_name, type_id, status_id, create_time, update_time, create_user_id, update_user_id', 'safe', 'on'=>'search'),
);
}
설명:1.인증 필드 가 사용자 에 게 입력 해 야 할 속성 입 니 다.사용자 가 입력 한 내용 이 아니 라 검증 할 필요 가 없습니다.
2.데이터베이스 에 있 는 작업 필드(시스템 에 의 해 생 성 되 더 라 도 생 성 시간,업데이트 시간 등 필드―boyLee 에서 제공 하 는 yii컴퓨터 소스 코드 에 서 는 시스템 생 성 된 이 속성 들 을 safe 에 두 지 않 았 습 니 다.아래 코드 참조).폼 이 제공 하지 않 은 데이터 에 대해 서 는 rules 방법 에서 검증 되 지 않 은 경우 safe 에 가입 해 야 합 니 다.그렇지 않 으 면 데이터 베 이 스 를 쓸 수 없습니다.
yii_컴퓨터 의 뉴스.php 모델 rules 방법
/**
* @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('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 rule is used by search().
// Please remove those attributes that should not be searched.
array('id, news_title, news_content, author_name, type_id, status_id', 'safe', 'on'=>'search'),
);
}
보기 에서 동적 내용 을 표시 하 는 세 가지 방법1.보기 파일 에서 직접 PHP 코드 로 이 루어 집 니 다.예 를 들 어 현재 시간 을 표시 합 니 다.보기에 서:
2.컨트롤 러 에서 내용 을 표시 하고 render 의 두 번 째 매개 변 수 를 통 해 보기 에 전달 합 니 다.컨트롤 러 방법 에 포함:
$theTime=date("Y-m-d H:i:s");
$this->render('helloWorld',array('time'=>$theTime));
보기 파일:
호출 된 render()방법 두 번 째 매개 변 수 는 array(배열 형식)입 니 다.render()방법 은 배열 의 값 을 추출 하여 보기 스 크 립 트 에 제공 합 니 다.배열 의 key(키)는 보기 스 크 립 트 에 제공 하 는 변수 이름 입 니 다.이 예 에서 배열 의 key(키 값)는 time 이 고 value(값)는$theTime 에서 추출 한 변수 이름$time 은 보기 스 크 립 트 에 사 용 됩 니 다.이것 은 컨트롤 러 의 데 이 터 를 보기 에 전달 하 는 방법 이다.3.보기 와 컨트롤 러 는 매우 긴밀 한 형제 이기 때문에 보기 파일 의$this 는 이 보 기 를 과장 하 는 컨트롤 러 를 말 합 니 다.앞의 예 시 를 수정 하고 컨트롤 러 에서 부분 변수 가 아 닌 공공 속성 을 정의 합 니 다.값 은 현재 날짜 와 시간 입 니 다.그리고 보기 에서$this 를 통 해 이러한 속성 에 접근 합 니 다.
보기 이름 지정 약속
보기 파일 이름 은 ActionID 와 같 으 십시오.하지만 이것 은 추천 하 는 명명 약속 이라는 것 을 기억 하 세 요.사실 보기 파일 이름 은 ActionID 와 같 을 필요 가 없고 파일 이름 을 첫 번 째 매개 변수 로 render()에 전달 하면 됩 니 다.
DB 관련
$Prerfp = Prerfp::model()->findAll(
array(
'limit'=>'5',
'order'=>'releasetime desc'
)
);
$model = Finishrfp::model()->findAll(
array(
'select' => 'companyname,title,releasetime',
'order'=>'releasetime desc',
'limit' => 10
)
);
foreach($model as $val){
$noticeArr[] = " ".$val->title." ,".$val->companyname." 。";
}
$model = Cgnotice::model()->findAll (
array(
'select' => 'status,content,updatetime',
'condition'=> 'status = :status ',
'params' => array(':status'=>0),
'order'=>'updatetime desc',
'limit' => 10
)
);
foreach($model as $val){
$noticeArr[] = $val->content;
}
$user=User::model()->find('LOWER(username)=?',array($username));
$noticetype = Dictionary::model()->find(array(
'condition' => '`type` = "noticetype"')
);
// postID=10
$post=Post::model()->find('postID=:postID', array(':postID'=>10));
$condition 을 사용 하여 더 복잡 한 조회 조건 을 지정 할 수도 있 습 니 다.문자열 을 사용 하지 않 습 니 다.$condition 을 CDbCriteria 의 인 스 턴 스 로 만 들 수 있 습 니 다.WHERE 에 국한 되 지 않 는 조건 을 지정 할 수 있 습 니 다.예 를 들 면:
$criteria=new CDbCriteria;
$criteria->select='title'; // 'title'
$criteria->condition='postID=:postID';
$criteria->params=array(':postID'=>10);
$post=Post::model()->find($criteria); // $params
CDbCriteria 를 검색 조건 으로 사용 할 때$params 인 자 는 더 이상 필요 하지 않 습 니 다.CDbCriteria 에서 위 와 같이 지정 할 수 있 기 때 문 입 니 다.CDbCriteria 를 대체 하 는 방법 은 find 방법 에 배열 을 전달 하 는 것 이다.배열 의 키 와 값 은 각각 대응 하 는 표준(criterion)의 속성 이름과 값 입 니 다.위의 예 는 다음 과 같이 다시 쓸 수 있 습 니 다.
$post=Post::model()->find(array(
'select'=>'title',
'condition'=>'postID=:postID',
'params'=>array(':postID'=>10),
));
기타1.링크
title,0,26),array('prerfp/details','id'=>$val->rfpid),array('target'=>'_blank'));?>
API 문서 찾기:CHtml 의 link()방법title,0,26); ?>
구체 적 으로 API 문 서 를 찾 으 십시오:CController 의 createUrl()방법위의 두 연결 효 과 는 같 습 니 다.
구성 요소 포함
하나의 예시:
보기 의 아래쪽 에 다음 코드 가 있 습 니 다:
widget ( 'Notice' ); ?>
protected/coponents 의 Notice.php 파일 을 엽 니 다.내용 은 다음 과 같 습 니 다.
<?php
Yii::import('zii.widgets.CPortlet');
class Banner extends CPortlet
{
protected function renderContent()
{
$this->render('banner');
}
}
렌 더 링 된 보기 banner 는 protected/coponents/views 디 렉 터 리 에 있 습 니 다.자세히 보기 API,키워드:CPortlet
현재 호스트 가 져 오기
Yii::app()->request->getServerName();
//and
$_SERVER['HTTP_HOST'];
$url = 'http://'.Yii::app()->request->getServerName(); $url .= CController::createUrl('user/activateEmail', array('emailActivationKey'=>$activationKey));
echo $url;
뉴스 를 발표 할 때 ckeditor 확장 자 를 추가 하 는 중 발생 하 는 상황 에 대하 여
$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프로젝트 디 렉 터 리 가 d:\wwwroot\\blog 디 렉 터 리 에 있다 면.위의 값 은 d:\www wroot\blog\\proctected 입 니 다.경로 에 주의 하 세 요.마지막 에 크로스 바 가 없습니다.
echo Yii::app()->baseUrl;
프로젝트 디 렉 터 리 가 d:\wwwroot\\blog 디 렉 터 리 에 있다 면.위의 값 은/blog 입 니 다.경로 에 주의 하 세 요.마지막 에 크로스 바 가 없습니다.
(d:\wwroot 는 사이트 루트 디 렉 터 리)위의 두 가지 차이 점 에 주의 하 십시오.하 나 는 basePath,하 나 는 baseUrl.
기타
컨트롤 러 A 에 대응 하 는 A 보기에 서 B 모델 의 방법 을 호출 합 니 다.B:model()->B 모델 의 방법 명()을 사용 합 니 다.
초기 에 파악 해 야 할 API 들
CHtml
본 고 는 Yii 프레임 워 크 를 기반 으로 한 PHP 프로 그래 밍 에 도움 이 되 기 를 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Y 분 에 에 랑 배우 기.[] 은 빈 목록 입 니 다.목록 에 있 는 요 소 를 추출 하기 위해 서 패턴 일치 동작 을 사용 할 수 있 습 니 다.만약 에 우리 가 비어 있 지 않 은 목록 L 이 있다 면 [X|Y] = L 은 L 의 hea...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.