thinkphp5.0은 편안한 스타일의 인터페이스 레이어를 빠르게 구축합니다(예제 분석)
下面由thinkphp框架教程栏目给大家介绍thinkphp5.0极速搭建restful风格接口层实例,希望对需要的朋友有所帮助!
下面是基于ThinkPHP V5.0 RC4框架,以restful风格完成的新闻查询(get)、新闻增加(post)、新闻修改(put)、新闻删除(delete)等server接口层。
1、下载ThinkPHP V5.0 RC4版本;
2、配置虚拟域名(非必须,只是为了方便);
Apache\conf\extra\httpd-vhosts.conf
<VirtualHost *:80> DocumentRoot "D:/webroot/tp5/public" ServerName www.tp5-restful.com <Directory "D:/webroot/tp5/public"> DirectoryIndex index.html index.php AllowOverride All Order deny,allow Allow from all </Directory> </VirtualHost>
3、开启伪静态支持.htaccess文件
apache方法:
a)在conf目录下httpd.conf中找到下面这行并去掉#
LoadModule rewrite_module modules/mod_rewrite.so
b)将所有AllowOverride None改成AllowOverride All
public\.htaccess文件内容:
<IfModule mod_rewrite.c> Options +FollowSymlinks -Multiviews RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php [L,E=PATH_INFO:$1] </IfModule>
4、创建测试数据
tprestful.sql
-- -- 数据库: `tprestful` -- -- -------------------------------------------------------- -- -- 表的结构 `news` -- CREATE TABLE IF NOT EXISTS `news` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(255) NOT NULL, `content` text NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='新闻表' AUTO_INCREMENT=1; -- -- 转存表中的数据 `news` -- INSERT INTO `news` (`id`, `title`, `content`) VALUES (1, '新闻1', '新闻1内容'), (2, '新闻2', '新闻2内容'), (3, '新闻3', '新闻3内容'), (4, '房价又涨了', '据新华社消息:上海均价环比上涨5%');
5、修改数据库配置文件
application\database.php
<?php return [ // 数据库类型 'type' => 'mysql', // 服务器地址 'hostname' => '127.0.0.1', // 数据库名 'database' => 'tprestful', // 用户名 'username' => 'root', // 密码 'password' => '123456', // 端口 'hostport' => '', // 连接dsn 'dsn' => '', // 数据库连接参数 'params' => [], // 数据库编码默认采用utf8 'charset' => 'utf8', // 数据库表前缀 'prefix' => '', // 数据库调试模式 'debug' => true, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) 'deploy' => 0, // 数据库读写是否分离 主从式有效 'rw_separate' => false, // 读写分离后 主服务器数量 'master_num' => 1, // 指定从服务器序号 'slave_no' => '', // 是否严格检查字段是否存在 'fields_strict' => true, // 数据集返回类型 array 数组 collection Collection对象 'resultset_type' => 'array', // 是否自动写入时间戳字段 'auto_timestamp' => false, // 是否需要进行SQL性能分析 'sql_explain' => false, ];
6、定义restful风格的路由规则,
application\route.php
<?php use think\Route; Route::get('/',function(){ return 'Hello,world!'; }); Route::get('news/:id','index/News/read'); //查询 Route::post('news','index/News/add'); //新增 Route::put('news/:id','index/News/update'); //修改 Route::delete('news/:id','index/News/delete'); //删除 //Route::any('new/:id','News/read'); // 所有请求都支持的路由规则
7、新建模型
application\index\model\News.php
<?php namespace app\index\model; use think\Model; class News extends Model{ protected $pk = 'id'; //protected static $table = 'news'; }
8、新建控制器
application\index\controller\News.php
<?php namespace app\index\controller; use think\Request; use think\controller\Rest; class News extends Rest{ public function rest(){ switch ($this->method){ case 'get': //查询 $this->read($id); break; case 'post': //新增 $this->add(); break; case 'put': //修改 $this->update($id); break; case 'delete': //删除 $this->delete($id); break; } } public function read($id){ $model = model('News'); //$data = $model::get($id)->getData(); //$model = new NewsModel(); $data=$model->where('id', $id)->find();// 查询单个数据 return json($data); } public function add(){ $model = model('News'); $param=Request::instance()->param();//获取当前请求的所有变量(经过过滤) if($model->save($param)){ return json(["status"=>1]); }else{ return json(["status"=>0]); } } public function update($id){ $model = model('News'); $param=Request::instance()->param(); if($model->where("id",$id)->update($param)){ return json(["status"=>1]); }else{ return json(["status"=>0]); } } public function delete($id){ $model = model('News'); $rs=$model::get($id)->delete(); if($rs){ return json(["status"=>1]); }else{ return json(["status"=>0]); } } }
9、测试
a)、访问入口文件,默认在public\index.php
b)、客户端测试restful的get、post、put、delete方法
client\client.php
<?php require_once './ApiClient.php'; $param = array( 'title' => '房价又涨了', 'content' => '据新华社消息:上海均价环比上涨5%' ); $api_url = 'http://www.tp5-restful.com/news/4'; $rest = new restClient($api_url, $param, 'get'); $info = $rest->doRequest(); //$status = $rest->status;//获取curl中的状态信息 $api_url = 'http://www.tp5-restful.com/news'; $rest = new restClient($api_url, $param, 'post'); $info = $rest->doRequest(); $api_url = 'http://www.tp5-restful.com/news/4'; $rest = new restClient($api_url, $param, 'put'); $info = $rest->doRequest(); echo '<pre/>'; print_r($info);exit; $api_url = 'http://www.tp5-restful.com/news/4'; $rest = new restClient($api_url, $param, 'delete'); $info = $rest->doRequest(); ?>
请求工具类
client\ApiClient.php
<?php class restClient { //请求的token const token='yangyulong'; //请求url private $url; //请求的类型 private $requestType; //请求的数据 private $data; //curl实例 private $curl; public $status; private $headers = array(); /** * [__construct 构造方法, 初始化数据] * @param [type] $url 请求的服务器地址 * @param [type] $requestType 发送请求的方法 * @param [type] $data 发送的数据 * @param integer $url_model 路由请求方式 */ public function __construct($url, $data = array(), $requestType = 'get') { //url是必须要传的,并且是符合PATHINFO模式的路径 if (!$url) { return false; } $this->requestType = strtolower($requestType); $paramUrl = ''; // PATHINFO模式 if (!empty($data)) { foreach ($data as $key => $value) { $paramUrl.= $key . '=' . $value.'&'; } $url = $url .'?'. $paramUrl; } //初始化类中的数据 $this->url = $url; $this->data = $data; try{ if(!$this->curl = curl_init()){ throw new Exception('curl初始化错误:'); }; }catch (Exception $e){ echo '<pre class="brush:php;toolbar:false">'; print_r($e->getMessage()); echo ''; } curl_setopt($this->curl, CURLOPT_URL, $this->url); curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1); //curl_setopt($this->curl, CURLOPT_HEADER, 1); } /** * [_post 设置get请求的参数] * @return [type] [description] */ public function _get() { } /** * [_post 设置post请求的参数] * post 新增资源 * @return [type] [description] */ public function _post() { curl_setopt($this->curl, CURLOPT_POST, 1); curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->data); } /** * [_put 设置put请求] * put 更新资源 * @return [type] [description] */ public function _put() { curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'PUT'); } /** * [_delete 删除资源] * delete 删除资源 * @return [type] [description] */ public function _delete() { curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'DELETE'); } /** * [doRequest 执行发送请求] * @return [type] [description] */ public function doRequest() { //发送给服务端验证信息 if((null !== self::token) && self::token){ $this->headers = array( 'Client-Token:'.self::token,//此处不能用下划线 'Client-Code:'.$this->setAuthorization() ); } //发送头部信息 $this->setHeader(); //发送请求方式 switch ($this->requestType) { case 'post': $this->_post(); break; case 'put': $this->_put(); break; case 'delete': $this->_delete(); break; default: curl_setopt($this->curl, CURLOPT_HTTPGET, TRUE); break; } //执行curl请求 $info = curl_exec($this->curl); //获取curl执行状态信息 $this->status = $this->getInfo(); return $info; } /** * 设置发送的头部信息 */ private function setHeader(){ curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->headers); } /** * 生成授权码 * @return string 授权码 */ private function setAuthorization(){ $authorization = md5(substr(md5(self::token), 8, 24).self::token); return $authorization; } /** * 获取curl中的状态信息 */ public function getInfo(){ return curl_getinfo($this->curl); } /** * 关闭curl连接 */ public function __destruct(){ curl_close($this->curl); } }
完整代码从我github下载:https://github.com/phper-hard/tp5-restful
위 내용은 thinkphp5.0은 편안한 스타일의 인터페이스 레이어를 빠르게 구축합니다(예제 분석)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











ThinkPHP 프로젝트를 실행하려면 다음이 필요합니다: Composer를 설치하고, 프로젝트 디렉터리를 입력하고 php bin/console을 실행하고, 시작 페이지를 보려면 http://localhost:8000을 방문하세요.

ThinkPHP에는 다양한 PHP 버전용으로 설계된 여러 버전이 있습니다. 메이저 버전에는 3.2, 5.0, 5.1, 6.0이 포함되며, 마이너 버전은 버그를 수정하고 새로운 기능을 제공하는 데 사용됩니다. 최신 안정 버전은 ThinkPHP 6.0.16입니다. 버전을 선택할 때 PHP 버전, 기능 요구 사항 및 커뮤니티 지원을 고려하십시오. 최상의 성능과 지원을 위해서는 최신 안정 버전을 사용하는 것이 좋습니다.

ThinkPHP Framework를 로컬에서 실행하는 단계: ThinkPHP Framework를 로컬 디렉터리에 다운로드하고 압축을 풉니다. ThinkPHP 루트 디렉터리를 가리키는 가상 호스트(선택 사항)를 만듭니다. 데이터베이스 연결 매개변수를 구성합니다. 웹 서버를 시작합니다. ThinkPHP 애플리케이션을 초기화합니다. ThinkPHP 애플리케이션 URL에 접속하여 실행하세요.

"개발 제안: ThinkPHP 프레임워크를 사용하여 비동기 작업을 구현하는 방법" 인터넷 기술의 급속한 발전으로 인해 웹 응용 프로그램은 많은 수의 동시 요청과 복잡한 비즈니스 논리를 처리하기 위한 요구 사항이 점점 더 높아졌습니다. 시스템 성능과 사용자 경험을 향상시키기 위해 개발자는 이메일 보내기, 파일 업로드 처리, 보고서 생성 등과 같이 시간이 많이 걸리는 작업을 수행하기 위해 비동기 작업을 사용하는 것을 종종 고려합니다. PHP 분야에서 널리 사용되는 개발 프레임워크인 ThinkPHP 프레임워크는 비동기 작업을 구현하는 몇 가지 편리한 방법을 제공합니다.

Laravel과 ThinkPHP 프레임워크의 성능 비교: ThinkPHP는 일반적으로 최적화 및 캐싱에 중점을 두고 Laravel보다 성능이 좋습니다. Laravel은 잘 작동하지만 복잡한 애플리케이션의 경우 ThinkPHP가 더 적합할 수 있습니다.

ThinkPHP 설치 단계: PHP, Composer 및 MySQL 환경을 준비합니다. Composer를 사용하여 프로젝트를 만듭니다. ThinkPHP 프레임워크와 종속성을 설치합니다. 데이터베이스 연결을 구성합니다. 애플리케이션 코드를 생성합니다. 애플리케이션을 실행하고 http://localhost:8000을 방문하세요.

ThinkPHP는 캐싱 메커니즘, 코드 최적화, 병렬 처리 및 데이터베이스 최적화와 같은 장점을 갖춘 고성능 PHP 프레임워크입니다. 공식 성능 테스트에 따르면 초당 10,000개 이상의 요청을 처리할 수 있으며 JD.com, Ctrip과 같은 대규모 웹 사이트 및 엔터프라이즈 시스템에서 실제 응용 프로그램으로 널리 사용됩니다.

개발 제안: API 개발을 위해 ThinkPHP 프레임워크를 사용하는 방법 인터넷이 지속적으로 발전하면서 API(응용 프로그래밍 인터페이스)의 중요성이 점점 더 커지고 있습니다. API는 데이터 공유, 함수 호출 및 기타 작업을 실현할 수 있으며 개발자에게 비교적 간단하고 빠른 개발 방법을 제공합니다. 뛰어난 PHP 개발 프레임워크인 ThinkPHP 프레임워크는 효율적이고 확장 가능하며 사용하기 쉽습니다.
