ThinkpHP 3.2.3 에서 ThinkpHP 5.0 으로 넘 어가 필기 도문 상세 설명 을 학습 합 니 다.

이 글 은 ThinkpHP 3.2.3 에서 ThinkpHP 5.0 학습 노트 로 넘 어 가 는 사례 를 담 고 있다.여러분 께 참고 하도록 공유 하 겠 습 니 다.구체 적 으로 는 다음 과 같 습 니 다.
tp 3.2.3 으로 많은 프로젝트 를 했 지만 시대 와 연결 되 고 새로운 구 조 를 배 워 야 한다.예 를 들 어 tp 5.
다음은 학습 과정 에서 발생 한 문제 와 해결 방법 을 기록 하고 tp 3.2 와 tp 5.0 의 차이 점 을 기록 하여 tp3 를 사용 해 보지 않 은 tp5 어린이 신발 에 참고 하기에 적합 합 니 다.
학습 이 끊임없이 갱 신 됨 에 따라...
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
먼저 tp 홈 페이지 에 가서 최신 ThinkPHP5.0.22 완전 판 을 다운로드 했다.

서버 에 직접 던 졌 습 니 다.압축 해제 후 디 렉 터 리 구 조 는 다음 과 같 습 니 다.

디 렉 터 리 구 조 는 전체적으로 tp 3.2 와 대동소이 하고 폴 더 의 이니셜 은 소문 자 이 며 입구 파일 을 사용 합 니 다. 루트 디 렉 터 리 아래 public/index.php,공식 문 서 는 Public 폴 더 를 WEB 배치 디 렉 터 리(대외 방문 디 렉 터 리)로 정의 합 니 다.

서버 도 메 인 이름 분석 을 설정 할 때 항목 루트 디 렉 터 리 를 가리 키 거나 public:

<VirtualHost *:80>
 ServerAdmin [email protected]
 DocumentRoot /var/www/tp/public
 ServerName tp.oyhdo.com
 ServerAlias tp.oyhdo.com
 DirectoryIndex index.php index.html index.htm 
</VirtualHost>
루트 디 렉 터 리 아래 application/config.php (공공)프로필 을 사용 하기 위해 자주 사용 하 는 설정 을 설정 합 니 다.다음은'프로필'이 라 고 부 릅 니 다.

인터넷 주 소 는 다음 과 같 습 니 다.

tp.oyhdo.com 에 접근 하 는 것 은 tp.oyhdo.com/index.php/index/index/index 에 접근 하 는 것 과 같 습 니 다.(기본적으로 대소 문 자 를 구분 하지 않 습 니 다)
즉,기본 모듈 index,기본 컨트롤 러 Index,기본 동작 index
프로필 수정 은 각각 defaultmodule、default_controller、default_action

url 대소 문 자 를 강제로 구분 하려 면 url 을 수정 하 십시오.convert 는 false:

프로필 에 app 설정debug 는 true 으로 디 버 깅 모드 를 열 어 디 버 깅 을 개발 할 수 있 습 니 다.

[url 의 index.php 입구 파일 숨 기기]
아파 치 서버 의 경우 아파 치 설정 파일 httpd.conf 에 mod 가 열 려 있 는 지 먼저 확인 합 니 다.rewrite.so 모듈:

그리고 모든[Allow Override]를 All 로 설정 합 니 다.

 마지막 으로 루트 디 렉 터 리 아래 Public/htaccess 파일 내용 을 수정 합 니 다.

<IfModule mod_rewrite.c>
 Options +FollowSymlinks -Multiviews
 RewriteEngine on
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule ^(.*)$ index.php?/$1 [QSA,PT,L]
</IfModule>
index.php 를 제거 해도 접근 할 수 있 습 니 다:

[프런트 url 모듈 명 숨 기기] 
index 모듈 을 프론트 데스크 톱 으로 하고 프론트 데스크 에 User 컨트롤 러 를 새로 만 들 었 습 니 다.

<?php
namespace app\index\controller;

class User
{
 public function user()
 {
 return '  User    user  ';
 }
}
 User 컨트롤 러 에 이렇게 접근 하 는 user 작업 이 필요 합 니 다.

 프론트 url 을 간결 하 게 표시 하기 위해 서 모듈 이름 index 를 제거 하고 붕 괴 됩 니 다.

모듈 이 하나 밖 에 없다 면/application/common.php 에 추가 할 수 있 습 니 다.

//        index  
define('BIND_MODULE','index');
직접 방문 성공:

그러나 프로젝트 는 보통 앞 배경 으로 구분 되 는데 적어도 두 개의 모듈 이 있다. 위의 방법 으로 index 모듈 을 연결 한 후 다른 모듈 에 방문 하면 오류 가 발생 합 니 다.
(배경 으로 admin 모듈 을 새로 만 들 었 습 니 다)

<?php
namespace app\admin\controller;

class Index
{
 public function index()
 {
 return '      ';
 }
}
 
다 중 모듈 의 경우/application/route.phop 에서 기본 모듈 경로(위의 단일 모듈 바 인 딩 제거)를 연결 할 수 있 습 니 다.

use think\Route;
Route::bind('index');
프론트 데스크 방문 성공:

 그리고/public/다음 에 입구 파일 admin.php 를 새로 만 들 고 배경 모듈 admin 을 연결 하여 배경 에 접근 합 니 다.

<?php
// [        ]
namespace think;
//       
define('APP_PATH', __DIR__ . '/../application/');
//         
require __DIR__ . '/../thinkphp/base.php';
//          admin  
Route::bind('admin');
//   admin     
App::route(false);
//     
App::run()->send();
배경 접근 성공:

(배경 주 소 를 수정 하려 면 이 파일 이름 만 수정 하면 됩 니 다)
 
[데이터 반환]
설정 파일 의 기본 출력 형식 default_return_type html:

 출력 문자열,배열 을 직접 인쇄 합 니 다.특별한 것 이 없습니다.

public function index()
{
 $str = 'hello,world!';
 $arr = array('state'=>1,'msg'=>'success');

 //     
 echo $str;

 //    
 var_dump($arr);
}

json 형식 데이터 되 돌려 주기:

public function index()
{
 $arr = array('state'=>1,'msg'=>'success');
 return json($arr);
 
 //             
 //return json($arr, 201, ['Cache-control' => 'no-cache,must-revalidate']);

 //xml  
 //return xml($arr);
}

(API 개발 만 하 는 경우 default 설정 가능return_type 은 json 이 며,직접 return $arr 으로 json 형식 데 이 터 를 되 돌려 줍 니 다)
 
[렌 더 링 템 플 릿,할당 데이터]
그림 에서 보기 층 을 만 들 면 index.html 는 프론트 데스크 톱 의 첫 페이지(내용 은'이것 은 첫 페이지')입 니 다.

tp3 렌 더 링 템 플 릿 은 컨트롤 러 에 $this->display() 이 고 tp5 는 지원 되 지 않 습 니 다.
tp5 렌 더 링 템 플 릿,컨트롤 러 에서 think\Controller 클래스 를 계승 하여 사용 합 니 다.  return $this->fetch()  조수 함수 사용 하기  return view()

<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
 public function index()
 {
 return $this->fetch();
 //return view();
 }
}

tp5 데이터 할당 방식 은 그대로 사용  $this->assign()

<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
 public function index()
 {
 	$name = 'lws';
 $this->assign('name',$name);
 return $this->fetch();
 }
}
index.html 페이지 읽 기 데이터:

{$name}

(템 플 릿 엔진 태그 설정 파일 수정【tpl 】begin】、【tpl_end】)

[부모 클래스 컨트롤 러 계승]
밤 을 쓰 고 Base 컨트롤 러 를 부모 컨트롤 러 로 새로 만 듭 니 다.Index 컨트롤 러 는 Base 컨트롤 러 를 계승 합 니 다.
부모 컨트롤 러 에서 분배 데 이 터 를 초기 화 합 니 다.하위 컨트롤 러 렌 더 링 템 플 릿:
Base.php:

<?php
namespace app\index\controller;
use think\Controller;
class Base extends Controller
{ 
 //     
 public function _initialize()
 {	
 	$haha = '    ';
 $this->assign('haha',$haha);
 }
}
Index.php:

<?php
namespace app\index\controller;
use think\Controller;
class Index extends Base
{
 public function index()
 {
 return $this->fetch();
 }
}
index.html:

{$haha}

(tp 3.2 에 비해 부모 컨트롤 러 는 Public 컨트롤 러 가 아 닙 니 다) 
【매개 변수 설정】
tp 3.2 에서 C 방법 으로 설정 하고 설정 파 라 메 터 를 가 져 옵 니 다.
tp5 조수 함수 사용  config()  설정,설정 매개 변수 가 져 오기:

//      
config('name','lws');

//      
config([
 'info'=>['sex'=>'nan','aihao'=>'nv']
]);

//        
echo config('name');

//        
dump(config('info'));

//          
echo config('info.sex');

[get 전 삼]
tp5 는 url/매개 변수 명 1/매개 변수 값 1/매개 변수 명 2/매개 변수 값 2 를 폐지 하 였 습 니 다.........................................................매개 변수 명 1=매개 변수 값 1&매개 변수 명 2=매개 변수 값 2...이렇게 전달 합 시다.
컨트롤 러 에서 $_GET 인쇄:

<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
 public function index()
 {
 $getdate = $_GET;
 dump($getdate);	
 }
}
 이렇게 하 는 것 은 옳지 않다.

이렇게 하면 쓰기 쉽다.

[안전 획득 변수] 
tp 3.2 I 방법 으로 get,post 등 시스템 입력 변 수 를 안전하게 가 져 올 수 있 습 니 다
tp5 에서 조수 함수 사용  input()

//  get  
$data1 = input('get.name');

//  post  
$data2 = input('post.name');

//        
$data3 = input('param.name');

//  request  
$data4 = input('request.name');

//  cookie  
$data5 = input('cookie.name');

//  session  
$data6 = input('session.name');

//        
$data7 = input('file.image');
(메모:가 져 온 데 이 터 는 배열 입 니 다./a 수식 자 를 더 해 야 가 져 올 수 있 습 니 다)

$arr = input('post.arr/a');
설정 파일 에 전역 필터 방법 을 설정 할 수 있 습 니 다:

//                 
'default_filter'  => 'htmlspecialchars',
[데이터베이스 조작]
tp5 데이터베이스 프로필 은 루트 디 렉 터 리/application/database.php:(모듈 에서 따로 설정 할 수도 있 습 니 다)

데이터베이스 연결:tp 3.2 지원 M 방법 으로 데이터베이스 연결,tp5 는 Db 클래스 또는 조수 함수
조회 데이터:여전히 사용  db()find()  방법,필드 조회 사용  select()  방법 대체 value()

//    
$artinfo = db('article')->find();

//    
$artinfo = db('article')->select();

//      
$artinfo = db('article')->value('article_title');
데이터 추가:tp 3.2 사용 getField(),tp5 사용  add():삽입 항목 수 를 되 돌려 줍 니 다.  혹시   insert():복귀 id

//      
$data['article_title'] = 'PHP         ';
$data['article_content'] = '  ';
db('article')->insert($data);
//  db('article')->save($data);

//      
$data = [
 ['article_title' => '  1', 'article_content' => '  1'],
 ['article_title' => '  2', 'article_content' => '  2'],
 ['article_title' => '  3', 'article_content' => '  3']
];
db('article')->insertAll($data);
수정 데이터:tp 3.2 사용 save(),tp5 사용  save()

//    
$whe['article_id'] = 1;
$data['article_title'] = '      ';
db('article')->where($whe)->update($data);
데이터 삭제:맞습니다.  update()

//    
$whe['article_id'] = 1;
db('article')->where($whe)->delete();
delete() 조 수 는 사용 하기에 비교적 편리 하지만 매번 데이터 베 이 스 를 다시 연결 하기 때문에 여러 번 호출 되 는 것 을 피해 야 하 며 Db 류 로 데이터 베 이 스 를 조작 하 는 것 을 권장 합 니 다.
Db 클래스 조작 원생 SQL:

<?php
namespace app\index\controller;
use think\Db;
class Index {
 public function index() {
 //     
 $res = Db::execute('insert into lws_article (title ,content) values ("  ", "  ")');
	
 //     
 $res = Db::execute('delete from lws_article where art_id = 1 ');

 //     
 $res = Db::execute('update lws_article set title = "    " where art_id = 1 ');

 //     
 $res = Db::query('select * from lws_article where art_id = 1');

 //        
 $res = Db::query('show tables from blog');

 //      
 $res = Db::execute('TRUNCATE table lws_article');
 }
}
Db 클래스 조작 조회 구조 기:

<?php
namespace app\index\controller;
use think\Db;
class Index {
 public function index() {
	//     (          )
	$res = Db::table('lws_article')
	 ->where('art_id', 1)
	 ->select();

	//            	

	//     
	$res = Db::name('article')
		->insert(['title' => '  ', 'content' => '  ']);

	//     
	$res = Db::name('article')
		->where('art_id', 1)
		->update(['title' => "    "]);

	//     
	$res = Db::name('article')
		->where('art_id', 1)
		->select();

	//     
	$res = Db::name('article')
		->where('art_id', 1)
		->delete();
 
 //      
 $artlist = Db::name('article')
	 ->where('is_del', 'N')
	 ->field('id,title,content')
	 ->order('post_time', 'desc')
	 ->limit(10)
	 ->select();
 } 
}
[데이터베이스 전환]
우선 데이터베이스 설정 에 여러 개의 데이터 베 이 스 를 설정 합 니 다.

//      1
'db1' => [
	//      
	'type' => 'mysql',
	//      
	'hostname' => '127.0.0.1',
	//     
	'database' => 'blog1',
	//       
	'username' => 'root',
	//      
	'password' => '123456',
	//        
	'hostport' => '',
	//        
	'params' => [],
	//          utf8
	'charset' => 'utf8',
	//       
	'prefix' => 'lws_',
],
//      2
'db2' => [
	//      
	'type' => 'mysql',
	//      
	'hostname' => '127.0.0.1',
	//     
	'database' => 'blog2',
	//       
	'username' => 'root',
	//      
	'password' => '',
	//        
	'hostport' => '',
	//        
	'params' => [],
	//          utf8
	'charset' => 'utf8',
	//       
	'prefix' => 'lws_',
],
connect 방법 으로 데이터베이스 전환:

<?php
namespace app\index\controller;
use think\Db;
class Index {
 public function index() {
 $db1 = Db::connect('db1');
 $db2 = Db::connect('db2');
 $db1->query('select * from lws_article where art_id = 1');
 $db2->query('select * from lws_article where art_id = 2');
 }
}
[시스템 상수]
tp5 상수 무더기 폐지:

REQUEST_METHOD IS_GET 
IS_POST  IS_PUT 
IS_DELETE IS_AJAX 
__EXT__  COMMON_MODULE 
MODULE_NAME CONTROLLER_NAME 
ACTION_NAME APP_NAMESPACE 
APP_DEBUG MODULE_PATH 
사용 해 야 할 상수,예 를 들 어 ISGET、IS_POST
나 는 부모 클래스 의 초기 화 방법 에서 이 두 상수 를 정의 했다.

<?php
namespace app\index\controller;
use think\Controller;
class Base extends Controller
{
 public function _initialize()
 {	
 	define('IS_GET',request()->isGet());
 define('IS_POST',request()->isPost());
 }
}
그리고 하위 컨트롤 러 에서 이 상수 로 판단 할 수 있 습 니 다.

<?php
namespace app\index\controller;
class Index extends Base
{
 public function index()
 { 
 if(IS_POST){
  echo 111;
 }else{
  echo 222;
 }
 }
}
[경로 정의]
예 를 들 어 블 로그 상세 페이지 의 원래 주 소 는 다음 과 같다.http://oyhdo.com/home/article/detial?id=50홈 모듈 에 있 는 article 컨트롤 러 에 있 는 detial 작업 방법 으로 매개 변수 id 를 전달 합 니 다.
경로 설정 파일 application/route.php 에 경로 규칙 을 추가 합 니 다:

return [
 'article/:id' => 'home/article/detial',
];
또는 Route 클래스 를 사용 하면 효과 가 같 습 니 다: 

use think\Route;
Route::rule('article/:id','home/article/detial');
경로 규칙 을 정의 한 후 접근 합 니 다.http://oyhdo.com/article/50...하면 된다

 【url 구분자 의 수정]
수정 하 다. application/config.php 적중 하 다 pathinfo_depr :

// pathinfo   
 'pathinfo_depr'  => '-',
웹 사이트 방문:http://oyhdo.com/article-50
[점프,방향 변경]
tp3 안의 정확 한 점프:db(),오류 점프:$this->success(),재 설정:$this->error(),tp5 에서 도 똑 같이 적용(계승\think\Controller)
tp5 에 $this->redirect() 조수 함 수 를 추가 하여 방향 을 바 꾸 는 데 사용 합 니 다:

return redirect('https://www.oyhdo.com');
thinkpHP 관련 내용 에 관심 이 있 는 독자 들 은 본 사이트 의 주 제 를 볼 수 있다.
본 고 는 ThinkPHP 프레임 워 크 를 기반 으로 한 PHP 프로 그래 밍 에 도움 이 되 기 를 바 랍 니 다.

좋은 웹페이지 즐겨찾기