Phalcon搭建多模块框架十:注册数据库服务及模型简单增删改查

首先创建一个数据库phalcon,然后创建一张表做测试。

CREATE TABLE `ph_robots` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(70) NOT NULL,
  `type` tinyint(1) NOT NULL,
  `weight` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

这里写图片描述
1、打开config/config.php
添加数据库配置

'db' => [
    'host' => 'localhost',
    'port' => 3306,
    'username' => 'root',
    'password' => '123456',
    'dbname' => 'phalcon',
    'charset' => 'utf8'
],

完整的config/config.php

<?php
/**
 * @desc 全局配置文件
 * @author zhaoyang
 * @date 2018年5月3日 下午7:54:47
 */
return [
    // 服务配置
    'services' => [
        // mysql数据库配置
        'db' => [
            'host' => 'localhost',
            'port' => 3306,
            'username' => 'root',
            'password' => '123456',
            'dbname' => 'phalcon',
            'charset' => 'utf8'
        ],
        // 调度器配置
        'dispatcher' => [
            // 处理 Not-Found错误配置
            'notfound' => [
                // 错误码及错误提示(ajax和post请求)
                'status_code' => 404,
                'message' => 'Not Found',
                // 错误跳转的页面
                'namespace' => DEFAULT_MODULE_NAMESPACE . '\\Controllers',
                'controller' => 'error',
                'action' => 'error404'
            ],
        ],
        // volt引擎相关配置
        'view_engine_volt' => [
            // 编译模板目录
            'compiled_path' => BASE_PATH . 'runtime/' . DEFAULT_MODULE . '/compiled/volt' . DS,
            // 是否实时编译
            'compile_always' => false,
            // 附加到已编译的PHP文件的扩展名
            'compiled_extension' => '.php',
            // 使用这个替换目录分隔符
            'compiled_separator' => '%%',
            // 是否要检查在模板文件和它的编译路径之间是否存在差异
            'stat' => true,
            // 模板前缀
            'prefix' => '',
            // 支持HTML的全局自动转义
            'autoescape' => false
        ],
        // 模板相关配置
        'view' => [
            // 模板后缀
            'view_suffix' => 'volt,phtml',
            // 模板路径
            'view_path' => APP_PATH . DEFAULT_MODULE . '/views' . DS,
            // 模板引擎,暂时支持viewEngineVolt or viewEnginePhp,与模板后缀一一对应
            'view_service' => 'viewEngineVolt,viewEnginePhp',
        ],
        // 过滤器设置
        'filter' => [
            // 过滤类型,支持string、trim、absint、int、email、float、int!、float!、alphanum、striptags、lower、upper、url、special_chars
            'default_filter' => 'string,trim'
        ],
    ],

];

2、打开config/services.php
注册数据库服务组件

use Phalcon\Db\Adapter\Pdo\Mysql;

$di->setShared('db', function () {
    $dbConfig = $this->getConfig()->services->db->toArray();
    $mysql = new Mysql($dbConfig);
    return $mysql;
});

完整的config/services.php

<?php
/**
 * @desc 注册服务
 * @author zhaoyang
 * @date 2018年5月3日 下午8:01:34
 */

use Common\Common;
use Common\Validate;
use Library\Extensions\VoltExtension;
use Library\Plugins\DIspatcherPlugin;
use Phalcon\Config;
use Phalcon\Db\Adapter\Pdo\Mysql;
use Phalcon\DI;
use Phalcon\Di\FactoryDefault;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\Router;
use Phalcon\Mvc\View;
use Phalcon\Mvc\View\Engine\Volt as ViewEngineVolt;
use Phalcon\Mvc\View\Engine\Php as ViewEnginePhp;

$di = new FactoryDefault();

/**
 * @desc 注册调度器服务
 * @author zhaoyang
 * @date 2018年5月3日 下午8:38:34
 */
$di->setShared('dispatcher', function () {
    $config = $this->getConfig();
    $dispatcher = new Dispatcher();
    $defaultNamespace = $config->module_default_namespaces ?? DEFAULT_MODULE_NAMESPACE . '\\Controllers';
    $dispatcher->setDefaultNamespace($defaultNamespace);
    $eventsManager = new EventsManager();
    $eventsManager->attach('dispatch', new DIspatcherPlugin());
    $dispatcher->setEventsManager($eventsManager);
    return $dispatcher;
});

/**
 * @desc 注册配置服务
 * @author zhaoyang
 * @date 2018年5月3日 下午8:38:53
 */
$di->setShared('config', function () use ($config) {
    return new Config($config);
});

/**
 * @desc 注册路由服务
 * @author zhaoyang
 * @date 2018年5月3日 下午8:39:06
 */
$di->setShared('router', function () use ($routerRules) {
    $router = new Router();
    // 自动删除末尾斜线
    $router->removeExtraSlashes(true);
    foreach ($routerRules as $k => $v) {
        $router->add($k, $v);
    }
    return $router;
});

/**
 * @desc 注册视图引擎volt服务
 * @author zhaoyang
 * @date 2018年5月4日 下午5:28:52
 */
$di->setShared('viewEngineVolt', function (View $view, DI $di) {
    // 获取config服务有多种方法,这是其一
    $voltConfig = $di->get('config')->services->view_engine_volt->toArray();
    $voltConfig = Common::convertArrKeyUnderline($voltConfig);
    $viewEngineVolt = new ViewEngineVolt($view, $di);
    $voltConfig['compiledPath'] = isset($voltConfig['compiledPath']) ? Common::dirFormat($voltConfig['compiledPath']) : BASE_PATH . 'runtime/' . DEFAULT_MODULE . '/compiled/volt' . DS;
    $mkdirRes = Common::mkdir($voltConfig['compiledPath']);
    if (!$mkdirRes) {
        throw new \Exception('创建目录 ' . $voltConfig['compiledPath'] . ' 失败');
    }
    $viewEngineVolt->setOptions($voltConfig);
    // 获取编译器对象
    $compiler = $viewEngineVolt->getCompiler();
    // 添加扩展
    $compiler->addExtension(new VoltExtension());
    return $viewEngineVolt;
});

/**
 * @desc 注册视图引擎php服务
 * @author zhaoyang
 * @date 2018年5月4日 下午5:29:15
 */
$di->setShared('viewEnginePhp', function (View $view, DI $di) {
    $viewEnginePhp = new ViewEnginePhp($view, $di);
    return $viewEnginePhp;
});

/**
 * @desc 注册视图服务
 * @author zhaoyang
 * @date 2018年5月3日 下午10:52:37
 */
$di->set('view', function () {
    // 获取config服务有多种方法,这是其二
    $viewConfig = $this->getConfig()->services->view;
    $viewDir = $viewConfig->view_path ?? APP_PATH . DEFAULT_MODULE . '/views' . DS;
    if (isset($viewConfig->view_suffix)) {
        $viewSuffixs = explode(',', $viewConfig->view_suffix);
    } else {
        $viewSuffixs = [ 
            'volt'
        ];
    }
    if (isset($viewConfig->view_service)) {
        $viewServices = explode(',', $viewConfig->view_service);
    } else {
        $viewServices = [ 
            'viewEngineVolt'
        ];
    }
    $engines = [ ];
    foreach ($viewSuffixs as $k => $v) {
        $suffix = '.' . ltrim($v, '.');
        $engines[$suffix] = $viewServices[$k] ?? $viewServices[0];
    }
    $view = new View();
    // 设置视图路径
    $view->setViewsDir($viewDir);
    // 注册视图引擎
    $view->registerEngines($engines);
    // 如果不需要“生成显示到控制器布局”和“生成显示到主布局”,则关闭这两个渲染级别
    $view->disableLevel([ 
        View::LEVEL_LAYOUT => true,
        View::LEVEL_MAIN_LAYOUT => true
    ]);
    return $view;
});

/** 
 * @desc 注册验证服务 
 * @author zhaoyang 
 * @date 2018年5月11日 下午7:26:30 
 */
$di->set('validate', function () {
    $validate = new Validate();
    return $validate;
});

/** 
 * @desc 注册数据库服务 
 * @author zhaoyang 
 * @date 2018年5月14日 下午9:01:36 
 */
$di->setShared('db', function () {
    $dbConfig = $this->getConfig()->services->db->toArray();
    $mysql = new Mysql($dbConfig);
    return $mysql;
});

至此已经配置完成,下面开始测试
3、在app/home/models下创建Robots.php模型文件

<?php
namespace App\Home\Models;

use Phalcon\Mvc\Model;

class Robots extends Model {

    public function initialize(){
        $this->setSource('ph_robots'); 
    }
}

4、在home模块添加RobotsController.php控制器

<?php
/**
 * @desc 主页
 * @author zhaoyang
 * @date 2018年3月23日 上午10:11:38
 */
namespace App\Home\Controllers;

use Common\BaseController;
use App\Home\Models\Robots;

class RobotsController extends BaseController {

    public function indexAction() {
        $robotsList = Robots::find();
        foreach ($robotsList as $robot){
            echo $robot->id,' ',$robot->name,' ',$robot->type,' ',$robot->weight,'<br/>';
        }
    }

    public function addAction() {
        $data = $this->get();
        $robots = new Robots();
        $res = $robots->create($data); // or save($data)
        var_dump($res, $robots->id ?? '插入失败', $robots->getMessages());exit;
    }

    public function infoAction() {
        $id = $this->get('id', 'int');
        $robot = Robots::findFirst($id);
        echo $robot->id,' ',$robot->name,' ',$robot->type,' ',$robot->weight;exit;
    }

    public function editAction() {
        $data = $this->get();
        $robot = Robots::findFirst($data['id']);
        $res = $robot->update($data); // or save($data)
        var_dump($res, $res ? '更新成功' : '更新失败', $robot->getMessages());exit;
    }

    public function deleteAction() {
        $id = $this->get('id', 'int');
        $robot = Robots::findFirst($id);
        $res = $robot->delete();
        var_dump($res, $res ? '删除成功' : '删除失败', $robot->getMessages());exit;
    }
}

访问/robots/add/name/robot_one/type/1/weight/13
这里写图片描述
数据库:
这里写图片描述
访问/robots/index
这里写图片描述
访问robots/info
这里写图片描述
访问/robots/edit/id/1/type/2
这里写图片描述
数据库:
这里写图片描述
访问/robots/delete/id/1
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值