管理后台-后端-PHP篇

这里选用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


我们先搭建基础环境

安装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
<?php

defined('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
<?php

class 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搭建管理后台

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
thinkPHP开发的后台管理系统 主要针对PHP入门级程序员开发适用,主要特点集成了AUTH多对多权限管理控制, 比较细分明确了 权限控制=》权限节点 、角色=》角色权限、管理员=》角色 的管理结构。 后台布局主要应用了Layuid的简明小清新,还支持5种风格切换、全屏浏览、锁屏等炫酷功能。 相信AndPHP.admin 能让你的后台开发也能舒爽起来,另外补充一点,对于目前大多的共享后台都集成封装了如表单、 列表等主要构件方法,说是为了方便快速布置后台,当对于入门来说,学习成本也是有的,阅读性也有牺牲,仁者见仁吧, 就是想告诉大家AndPHP.admin没有这样做,主要好处,多查阅ThinkPHP5.1及Layui2.x文档根据已有文件基本就能活学应用啦!! ( 打脸了,admin2.0对于FORM\LIST进行了方法集成,但保留了1.0的部分硬编输出,你可以更好的应对,快速的开发!) //============= AndPHP内容管理系统基于ThinkPHP、结合Layui等优秀开源项目开发; 将包含系统设置,权限管理,模型管理,数据库管理,栏目管理,会员管理,网站功能,模版管理,微信管理等相关模块。 官网在线演示: http://andphp.com 测试账号:test 测试密码:123456 admin2.0纯净版发布了 ThinkPHP核心框架更新至5.1.12, 精简后台功能模块,极简方便开发者 =)基于后台管理员登录/AUTH权限管理/系统配置及后台FORM、LIST公共方法 =)基于前台用户登录/AUTH权限管理/会员中心(集成积分管理、签到等)基本用户操作属性 =) 集成一键安装,localhost/install/index.php 轻度强迫症的我对代码规范有这一定的要求,所以一定程度上做好了备注标示,目前文档整理中,有问题请进QQ群交流学习! About, AndPHP采用ThinkPHP5.15开发,ThinkPHP5.15采用全新的目录结构、架构思想,引入了 很多 的PHP新特性,优化了核心,减少了依赖,实现了真正的惰性加载。 正因为ThinkPHP的 这些新特性, 从而使得ANDPHP的执行速度成倍提高。 UI方面,AndPHP采用了最受欢迎的Layui,Layui用于开发响应式布局、移动设备优先的 WEB 项目。 简洁、直观、强悍的前端开发框架,让ANDPHP后台界面更加美观,前台布局 更加爽快,开发更迅速、简单。 Tell U, 我们的目标:致力于为个人和中小型企业打造全方位的PHP企业级开发解决方案。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值