Phalcon 笔记(一)

阅读数:2402 发布时间:2016-07-23 12:03:32

作者:zzl005 标签: 朱忠来005 Mysql PHP Phalcon

加载器Loader

$loader = new PhalconLoader();

$loader->registerDirs(array('../apps/controllers/', '../apps/models/'));注册自动加载的类目录,为方便使用,在php解析程序启动时直接加载

$loader->register();Loader也要注册自身

依赖注入器(DI)

$di = new PhalconDI();依赖注入器。在这里,依赖注入(DI)模块是个容器。

数据库对象

$di->set('db', function(){
    return new PhalconDbAdapterPdoMysql(array(
        "host" => "192.168.0.103",
        // "host" => "localhost",
        "username" => "root",
        "password" => "",
        // "password" => "l",
        // "dbname" => "w3ljn",
        "dbname" => "xiuwai_database",
        "charset" => "utf8",
        'unix_socket' => '/tmp/mysql.sock'
    ));
});

模型(models)

实例:models/Cart.php

模型层是用来与数据存储打交道的,大多数情况下,一个model对应一张表

source表示表名,setSource设置,getSource获取

use PhalconMvcModel,
    PhalconMvcModelMessage,
    PhalconMvcModelValidatorInclusionIn,
    PhalconMvcModelValidatorUniqueness;

class Cart extends Model
{
  public $cart_id;
   public $uid;
   public $goods_id;
   public $put_time;
   public $number;
   public $brand_id;

   public function getSource()
   {
       return 'cart_tbl';
   }

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

}

注:

  1. 需要注意的是模型类必须继承PhalconMVCModel类,并且采用与数据库表名一致的驼峰命名法
  2. 而且类名不能含有下划线

数据库操作(两种方式)

在Phalcon中操作数据库提供了基本的ORM映射方式以及更加复杂的PHQL方式

$app->get('/say/cart/{cart_id}', function($cart_id) {
    $cart = Cart::findFirst("cart_id = '".$cart_id."'");
    $result = [
            'uid' => $cart->uid,
            'number' => $cart->number,
            'cart_id' => $cart->cart_id,
            'goods_id' => $cart->goods_id,
            'put_time' => $cart->put_time,
            'brand_id' => $cart->brand_id,
    ];
    echo json_encode($result);
});
$app->get('/api/robots2', function() use ($app){
    $query  = $app->modelsManager->createQuery("SELECT * FROM Cart");
    $cart   = $query->execute();
    echo json_encode($cart[0]);
});

相关文章推荐: