博客列表 >案例:原生php新浪微博(企业设计流程 db类的设计)2019年3月6日22时

案例:原生php新浪微博(企业设计流程 db类的设计)2019年3月6日22时

小明的博客
小明的博客原创
2019年07月22日 09:47:18725浏览

今天,进入了实战项目,主要学习了企业项目设计流程、db类的设计。

一、企业项目设计流程

  • 项目经理确认需求

  • ui设计出psd图

  • 前端完成静态页面

  • 后端设计数据库、完成PHP功能

二、db类的设计

  • 创建db类在index.php引入,这里需要在index.php,需要注意的是$_SERVER['DOCUMENT_ROOT']是文件的根目录,这里同web服务器设置有关,目前的更目录在htcdocs。

实例

require_once $_SERVER['DOCUMENT_ROOT'].'/weibo/lib/Db.php';

运行实例 »

点击 "运行实例" 按钮查看在线实例

  • 都是链式操作,所以每个方法里面都需要返回当前对象;

  • 需要创建 table  where  field  order  limit  item  lists

  • item方法思路,连接数据库,设置查询语句,得出查询结果;

  • 利用table where field order limit方法中通过设置类属性然后将响应的值在sql中引用;

  • item  lists 有大量代码重复  为了精简带码  设置init方法连接数据库,同时初始化where field limit order都在table中初始化

错误提示:$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

实例

<?php

class Db {

    //初始化pdo
    private function init () {
        //设置dns
        $dns = 'mysql:dbname=test';
        $username = 'root';
        $psw = 'root';
        //连接数据库
        $this->pdo = new PDO($dns, $username, $psw);
        //显示错误提示
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $this;
    }
    //查询表
    public function table ($table) {
        $this->init();
        $this->field = '*';
        $this->order = 'id desc';
        $this->table = $table;
        return $this;
    }
    //查询字段
    public function field ($field) {
        $this->field = $field;
        return $this;
    }
    //查询条件
    public function where ($where) {
        $this->where = $where;
        return $this;
    }
    //排序
    public function order ($order) {
        $this->order = $order;
        return $this;
    }
    //limit
    public function limit () {

    }
    //单条结果
    public function item () {

        //sql语句
        $sql = "SELECT {$this->field} FROM {$this->table} WHERE {$this->where} ORDER BY {$this->order} LIMIT 1";
//        exit($sql);
        //准备对象
        $stmt =  $this->pdo->prepare($sql);
        //执行
        $stmt->execute();
        //输出结果集
        $item = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $item ? $item[0] : false;

    }
    //结果集
    public function lists() {
        //sql语句
        $sql = "SELECT {$this->field} FROM {$this->table} WHERE {$this->where}";
//        exit($sql);
        //准备对象
        $stmt =  $this->pdo->prepare($sql);
        //执行
        $stmt->execute();
        //输出结果集
        $item = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $item ? $item[0] : false;
    }
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

总结:

  • 要掌握企业化流程,实现统一化,标准化,方便以后开发重复利用和维护;

  • db类复习了之前的php的类操作、sql操作,需要进一步掌握面向对象的变成思维


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议