这里选用codeigniter做为web框架,因为它安装方便(独立压缩包解压即可)、自身集成了migration,query-builder(对数据库的封装,不用关心数据库选型),虽然CI官方说明PHP版本只要求5.2,但是CI的第三方库ci-restserver要求5.4以上,另外PHP5.4以后加入了一个功能Built-in web server,我们可以脱离apache,直接在命令行通过php -S指令启动PHP测试服务器,本文的PHP版本将使用5.6


我们先搭建基础环境

  • 软件环境:
    PHP5.6
    Codeigniter3.0.3
    codeigniter-restserver

安装PHP

> rpm -Uvh http://repo.webtatic.com/yum/el6/latest.rpm
> yum install -y php56w php56w-pdo 

纠正PHP的时区

# /etc/php.ini
...
date.timezone = 'Asia/Shanghai'

安装CodeIgniter

> wget https://github.com/bcit-ci/CodeIgniter/archive/3.0.3.zip
> unzip 3.0.3.zip
> cd CodeIgniter-3.0.3/
> php -S 0.0.0.0:8000

访问该后台,顺利的话应该出现如下界面


数据库建模

1)配置数据库连接,并配置自动加载数据库模块

// application/config/database.php
$db['default'] = array(...'hostname' => 'sqlite:'.APPPATH.'db.sqlite3','dbdriver' => 'pdo',...
);
// application/config/autoload.php
...
$autoload['libraries'] = array("database");
...

2)启动migration,默认CI使用时间戳规定版本号,简单起见我们使用序列号sequential模式

// application/config/migration.php
$config['migration_enabled'] = TRUE;
$config['migration_type'] = 'sequential';

3)编写News表的migration

// application/migrations/001_add_news.php
<?phpdefined('BASEPATH') OR exit('No direct script access allowed');class Migration_Add_News extends CI_Migration {public function up(){$this->dbforge->add_field(array('id' => array('type' => 'INT','constraint' => 5,'unsigned' => TRUE,'auto_increment' => TRUE),'title' => array('type' => 'VARCHAR','constraint' => '100',),'content' => array('type' => 'TEXT','null' => TRUE,),'create_time' => array('type' => 'DATETIME',),));$this->dbforge->add_key('id', TRUE);$this->dbforge->create_table('news');}public function down(){$this->dbforge->drop_table('news');}
}

4)创建migrate入口

// application/controllers/Migrate.php
<?phpclass Migrate extends CI_Controller
{public function index(){$this->load->library('migration');if (!$this->migration->latest()){show_error($this->migration->error_string());}}}

5)CLI执行migrate

> php index.php migrate

用codeigniter-restserver搭建最简单的CRUD

首先我们从https://github.com/chriskacerguis/codeigniter-restserver下载并解压源码包(假设已经解压到了/tmp/),复制相关文件到对应目录

> cp /tmp/codeigniter-restserver-master/application/libraries/Format.php application/libraries/
> cp /tmp/codeigniter-restserver-master/application/libraries/REST_Controller.php application/libraries/
> cp /tmp/codeigniter-restserver-master/application/config/rest.php application/config/
> cp /tmp/codeigniter-restserver-master/application/language/english/rest_controller_lang.php application/language/english/

编写CRUD的controller

// application/controllers/News.php
<?php
require APPPATH . '/libraries/REST_Controller.php';
class News extends REST_Controller{public function index_post(){$this->db->set("title",$this->post("title"));$this->db->set("content",$this->post("content"));$this->db->set("create_time",date('Y-m-d H:i:s'));$this->db->insert("news");$this->set_response(['id'=>$this->db->insert_id()], REST_Controller::HTTP_CREATED);}public function index_get(){$id = $this->get("id");if($id!=null){$this->response($this->db->get_where("news",array('id'=>$id))->result()[0]);}else{$this->response($this->db->get("news")->result());}}public function index_put(){$this->db->set("title",$this->put("title"));$this->db->set("content",$this->put("content"));$this->db->where("id",$this->get("id"));$this->db->update("news");$this->set_response('', REST_Controller::HTTP_NO_CONTENT);}public function index_delete(){$this->db->where("id",$this->get("id"));$this->db->delete("news");$this->set_response('', REST_Controller::HTTP_NO_CONTENT);}
}
// application/config/routes.php
...
$route['news/(:num)'] = 'news/index/id/$1'; 

接下来我们需要用postman来测试接口(如何使用postman工具测试不在本文范畴),伪测试代码如下

> curl POST /news/       #Create
> curl GET /news/        #Read list
> curl GET /news/:id/    #Read item
> curl PUT /news/:id/    #Update
> curl DELETE /news/:id/ #Delete

接下来我们来整合BasicAuth验证功能

// application/config/rest.php
...
$config['rest_auth'] = 'basic';
$config['auth_source'] = '';
...

仅为演示,我们在rest.php里面配置了默认的帐号admin,密码是默认的1234。
我们再访问一下接口,服务器将返回401错误,浏览器根据该错误将弹出认证界面


按照制定的接口文档,我们再补全一个认证接口给客户端登录使用

// application/controllers/Auth.php
<?php
require APPPATH . '/libraries/REST_Controller.php';
class Auth extends REST_Controller{public function info_get(){$this->response(['name' => 'admin',]);}
}

书写扩展的协议-批量删除

// application/controllers/News.php
...
class News extends REST_Controller{...public function deletes_delete(){$ids = split(",",$this->input->get("ids"));foreach($ids as $id){$this->db->where("id",$id);$this->db->delete("news");}$this->set_response('', REST_Controller::HTTP_NO_CONTENT);}
}

书写扩展协议-搜索+分页

// application/controllers/News.php
...
class News extends REST_Controller{public $PAGE_SIZE = 50;...public function index_get(){$id = $this->get("id");if($id!=null){$this->response($this->db->get_where("news",array('id'=>$id))->result()[0]);}else{$search = $this->get("search");$page = $this->get("page");if($page==null)$page="1";$page = intval($page);$this->db->like('title',$search);$total_count = $this->db->count_all_results("news");$page_count = floor($total_count/$this->PAGE_SIZE);if($total_count%$this->PAGE_SIZE>0)$page_count++;$this->db->like('title',$search);$this->db->order_by("create_time",'DESC');$offset = $this->PAGE_SIZE*($page-1);$this->db->limit($this->PAGE_SIZE,$offset);$results = $this->db->get("news")->result();$data = ["total_count" => $total_count,"page_count" => $page_count,"next" => $page<$page_count,"previous" => $page>1,"results" => $results,];$this->response($data);}}
}

后端基本完成了,还剩下最后一个问题CORS,我们在本地写一个简单的jquery

<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<script>
$.get("http://172.17.9.177:8000/news/");
</script>

在chrome里面调试一下会出现如下错误

XMLHttpRequest cannot load http://172.17.9.177:8000/news/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401.

我们改造构造函数来加入CORS处理

// application/controllers/News.php
class News extends REST_Controller{...function __construct() {header('Access-Control-Allow-Origin: *');header("Access-Control-Allow-Headers: Authorization,Content-Type");header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");$method = $_SERVER['REQUEST_METHOD'];if($method == "OPTIONS") {die();}parent::__construct();}}

同样方法处理Auth.php,再次用jquery测试,之前那个错误将不再出现。

此文数据库模型、协议的定义参见用Angular搭建管理后台

管理后台-后端-PHP篇相关推荐

  1. php后端管,管理后台-后端-PHP篇

    这里选用codeigniter做为web框架,因为它安装方便(独立压缩包解压即可).自身集成了migration,query-builder(对数据库的封装,不用关心数据库选型),虽然CI官方说明PH ...

  2. 3. 在WordPress管理后台撰写第一篇博客文章

    3. 发布第一篇博客文章 在前面的文章中,我们首先介绍了1. 购买云服务器和域名的基本操作,然后又成功2. 搭建最简单的博客网站,如果你还没完成上面这些操作,请提前点击查看. 这篇文章我们首先熟悉下网 ...

  3. 如何用AngularJS构建管理后台

    前言 一般来说,一个管理后台的构建的基本流程是:(1)选择一个开发语言->(2)选择一种数据库->(3)选择一个开发轮子(framework)->(4)在轮子上搭建前端框架-> ...

  4. 基于Vue的管理后台设计(布局篇)

    文章系列: 基于Vue的管理后台设计(布局篇) 基于Vue的管理后台设计(登录鉴权篇) 基于Vue的管理后台设计(打包部署篇) 前言 我打算把接下来要写的几篇文章写成一个系列,用来记录一下如何基于Vu ...

  5. 08-Django-基础篇-admin管理后台

    admin管理后台 前言 管理后台使用 1. .创建管理员 2. .注册模型类 3. .发布内容到数据库 前言 本篇来学习Django自带的admin管理后台 管理后台使用 使用Django的管理模块 ...

  6. 基于VUE+DJANGO开发的前后端分离的官方网站系统带管理后台

    前言 每个企业都有开发一个官方网站的需求,用于展示企业的产品和服务,企业的文化宗旨和品牌形象等,并要求网站有比较强的自由定制的功能.为此,我开发了这款官方网站系统,自带轻便的管理后台,在后台简单修改下 ...

  7. 为啥我从后台查到的值在页面显示的是undefined_再谈一个管理后台列表功能应有的素质...

    ​大家能看到的这个号第1篇文章<无心朝政,列表功能分析下>就是讲列表功能.虽然当时写的时候特别认真,但基本是围绕"列表功能"这个广泛的词来阐述的. 最近在做一个体育赛事 ...

  8. 10 个 GitHub 上超火和超好看的管理后台模版,后台管理项目有着落了

    大家好,我是你们的 超级猫,一个不喜欢吃鱼.又不喜欢喵 的超级猫 ~ 前言 一般人没事的时候刷刷朋友圈.微博.电视剧.知乎,而有些人是没事的时候刷刷 GitHub ,看看最近有哪些流行的项目. 久而久 ...

  9. 使用 WorkManager 管理后台和前台工作

    ​​ 随着设备性能提升和软件生态发展,越来越多的 Android 应用需要执行相对更复杂的网络.异步和离线等任务.例如用户想要离线观看某个视频,又不想一直停留在应用界面等待下载完成,那么就需要以一定的 ...

最新文章

  1. python ui自动化配置文件,python UI自动化实战记录八:添加配置
  2. 高阶奇异值分解(HOSVD)理解
  3. vector iterator not incrementable 的问题
  4. 介绍一个统计各个网站访问时长的Chrome扩展 - Rooster
  5. 【学生选课系统经典】C#与SQLSERVER连接:ASP.NET网站(服务器端,IIS发布)
  6. .net性能测试和优化1 基本概念
  7. 日均5亿查询量的京东订单中心,为什么舍MySQL用ElasticSearch?
  8. mysql 5.5 特性_MySQL5.5复制新特性
  9. [转]python3_unboundlocalerror报错原因
  10. Layui form 表单验证 基本属性
  11. 最新版vmWare的安装后如何新建虚拟机
  12. Java反射05 : 修饰符Modifier静态方法学习示例
  13. BZOJ 3772: 精神污染
  14. 聚齐乐服务器维护时间多久,9月19日服务器例行维护更新公告(已完成)
  15. java实现分数四则运算
  16. 光猫桥接后宽带降速问题解决
  17. 数学中任意与存在符号的来历
  18. 卧槽!GitHub标星7.9K star,抢茅台酒脚本竟然开源了!网友:已抢到,真香!
  19. unity3D游戏开发实战原创视频讲座系列13之帽子戏法游戏开发(预告)
  20. 也谈时间管理和GTD

热门文章

  1. 职场PUA:为什么你就不能逼自己一把呢?
  2. Hbase的Hmaster高可用分布式报错probably a clock skew
  3. 通过冥想解除困意,提升精神
  4. 关于U盘烧录iso问题
  5. ASP.NET Core WebApi构建API接口服务实战演练
  6. 百度谷歌一起搜 - 百Google度 - Chrome插件
  7. 一些好用的手机软件分享
  8. MapServer 7.0.3 Documentation 翻译
  9. Revit导出PDF格式图纸流程及“批量导出图纸”
  10. MySQL-V5.7 压缩包版安装教程