phalcon-自用小例子-阿里云开发者社区

开发者社区> 开发与运维> 正文

phalcon-自用小例子

简介: phalcon安装 这里就不再说明windows下phalcon怎么安装了,ubuntu请自行加上 sudo 通用平台下安装指定的软件包: # Ubuntu sudo apt-get install php5-dev libpcre3-dev gcc make php5-mysql

phalcon安装

这里就不再说明windows下phalcon怎么安装了,ubuntu请自行加上 sudo

通用平台下安装指定的软件包:

# Ubuntu
sudo apt-get install php5-dev libpcre3-dev gcc make php5-mysql

# CentOS
sudo yum install php-devel pcre-devel gcc make

创建扩展:

git clone --depth=1 git://github.com/phalcon/cphalcon.git
cd cphalcon/build
./install

添加扩展到你的php配置文件:

extension=phalcon.so

然后重启php-fpm

service php-fpm restart

PhalconTools工具

phpstrom是通过IDEA定制的php开发工具,也是官方推荐的开发工具

  1. 首先我们要下载phalcon-devtools包并且解压

    下载地址:phalcon-devtools

    也可以在 教程代码库:http://git.oschina.net/wenzhenxi/Phalcon-tutorial本篇教程代码中下载

  2. phpstrom导入下载好的开发工具

  3. d7f2ab5de99a659450705b89d5d12545f4b45556

  4. 如上图所示,右键单击“External Libraries”,选择“Configure PHP Include Paths”,弹出如下操作框:

  5. 6d992342dbc4ba11443631b7825c93b120f60f92

  6. 单点“+”按钮,在弹出的操作框中,选择到刚才phalcon-devtools的解压目录,然后双击选中“/ide/任一Phalcon版本/Phalcon/”目录,点击“应用”和“确定”即可。如上图所示,我选择的是2.0.8版本。

  7. phpstorm自动提示Phalcon语法

  8. 76ab10ad1e20600a0cb4dee50eefe1e57d7ceb62

log-日志


use Phalcon\Logger\Adapter\File as FileAdapter;
$logger = new FileAdapter("../Runtime/log/2016-2/20160203.log");  //初始化文件地址
$logger->log("This is a message");                                  //写入普通log
$logger->log("This is an error", \Phalcon\Logger::ERROR);         //写入error信息
$logger->error("This is another error");                          //于上一句同义

// 开启事务
$logger->begin();

// 添加消息
$logger->alert("This is an alert");
$logger->error("This is another error");

//  保存消息到文件中
$logger->commit();

 <?php

 use Phalcon\Logger;
 use Phalcon\Logger\Multiple as MultipleStream;
 use Phalcon\Logger\Adapter\File as FileAdapter;
 use Phalcon\Logger\Adapter\Stream as StreamAdapter;

 $logger = new MultipleStream();

 $logger->push(new FileAdapter('test.log'));
 $logger->push(new StreamAdapter('php://stdout'));

 $logger->log("This is a message");
 $logger->log("This is an error", Logger::ERROR);
 $logger->error("This is another error");


 use Phalcon\Logger\Formatter\Line as LineFormatter;

 // 修改日志格式
 $formatter = new LineFormatter("[%date%] - [%message%]");
 $logger->setFormatter($formatter);
 //这样配置获得log结果如下 
 //[Wed, 03 Feb 16 11:20:13 +0800] - [This is another error]

 use Phalcon\Logger;
 use Phalcon\Logger\Adapter\Firephp as Firephp;

 $logger = new Firephp("");
 $logger->log("This is a message");
 $logger->log("This is an error", Logger::ERROR);
 $logger->error("This is another error");


session


use Phalcon\Session\Adapter\Files as Session;

//实例化session并且开始 赋值给DI实例 方便在控制器中调用
$di->setShared('session', function () {
    $session = new Session();
    $session->start();
    return $session;
});



$this->session->set('username', 'miao');
$this->session->username = 'miao';

echo $this->session->get('username');
echo $this->session->username;

$this->session->remove("username");
$this->session->destroy();

HTTP请求


$request = $this->request;

var_dump($request->get());                          //默认获取所有的请求参数返回的是array效果和获取$_REQUEST相同
var_dump($request->get('wen'));                     //获取摸个特定请求参数key的valuer和$_REQUEST['key']相同
var_dump($request->getQuery('url', null, 'url'));   //获取get请求参数,第二个参数为过滤类型,第三个参数为默认值
var_dump($request->getMethod());                    //获取请求的类型如果是post请求会返回"POST"
var_dump($request->isAjax());                       //判断请求是否为Ajax请求
var_dump($request->isPost());                       //判断是否是Post请求类似的有(isGet,isPut,isPatch,isHead,isDelete,isOptions等)
var_dump($request->getHeaders());                   //获取所有的Header,返回结果为数组
var_dump($request->getHeader('Content-Type'));      //获取Header中的的莫一个指定key的指
var_dump($request->getURI());                       //获取请求的URL比如phalcon.w-blog.cn/phalcon/Request获取的/phalcon/Request
var_dump($request->getHttpHost());                  //获取请求服务器的host比如phalcon.w-blog.cn/phalcon/Request获取的phalcon.w-blog.cn
var_dump($request->getServerAddress());             //获取当前服务器的IP地址
var_dump($request->getRawBody());                   //获取Raw请求json字符
var_dump($request->getJsonRawBody());               //获取Raw请求json字符并且转换成数组对象
var_dump($request->getScheme());                    //获取请求是http请求还是https请求
var_dump($request->getServer('REMOTE_ADDR'));       //等同于$_SERVER['REMOTE_ADDR']

header
 //Header类
$headers = $response->getHeaders();                         //获取Headers实例
$headers->set('header1', 'header1');                        //写入header实例一个header头
$response->setHeaders($headers);                            //设置一组返回的headers头
$response->getHeaders();                                    //查看当前的headers头
$response->setHeader('header2', 'header2');                 //单独设置一个返回的header头

跳转


//跳转类
//$response->redirect("Request/Index");                     //跳转到这个内部的Request模块Index方法(注意需要设置URL不然会跳转到public显示404)
//$response->redirect("http://www.baidu.com", true);        //跳转到这个外部地址
//$response->redirect("http://www.baidu.com", true, 302);   //跳转到这个外部地址并且给当前页面一个状态码

return 


  //return类
//$response->appendContent('test');                          //添加一段返回类容
//$response->setJsonContent(array('Response' => 'ok'));      //返回一个json,参数必须是数组
//$response->setContent("<h1>Hello!</h1>");                  //返回需要显示在页面上的内容
//$response->setStatusCode(404, "Not Found");                //返回http请求状态,以及msg
//return $response->send();

转发


public function index2Action() {

    $this->flash->error("当前用户尚无访问权限!");

    // 跳转到指定的控制器和方法
    $this->dispatcher->forward(array(
        "controller" => "Controller",
        "action"     => "index"
    ));

    echo '<h1>Controller/index2!</h1>';
}

钩子函数


public function beforeExecuteRoute($dispatcher) {

    echo '<h1>beforeExecuteRoute!</h1>';
}

public function afterExecuteRoute($dispatcher) {

    echo '<h1>afterExecuteRoute!</h1>';
}


Model

注意:phalcon当前DB类不支持mssql


use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;

// 初始化数据库连接 从配置项读取配置信息
$di->set('db', function () use ($ConfigIni) {

    return new DbAdapter(array(
        "host"     => $ConfigIni->database->host,
        "username" => $ConfigIni->database->username,
        "password" => $ConfigIni->database->password,
        "dbname"   => $ConfigIni->database->dbname
    ));
});


添加


public function insertAction() {

    $User = new  User();

    //设置需要写入的数据
    //如果在model里面没有设置公共变量,对这边的使用也没有影响但是对IDE有良好的提示功能
    $User->name   = "phalcon";
    $User->phone  = "13011111111";
    $User->passwd = "passwd";
    //执行操作
    $ret = $User->save();

    //对结果进行验证
    if ($ret) {
        echo "写入数据成功";
    } else {
        //如果插入失败处理打印报错信息
        echo "写入数据库失败了";
        foreach ($User->getMessages() as $message) {
            echo $message->getMessage(), "<br/>";
        }
    }

    echo '<h1>BasemodelController/select!</h1>';
}

查询


public function selectAction() {

    $rs = User::find(1);
    var_dump($rs->toArray());
    echo '<h1>BasemodelController/select!</h1>';
}


$rs = User::query()
    ->where("name = :name:")
    ->andWhere("phone  = 13011111111")
    ->bind(array("name" => "phalcon"))
    ->order("phone")
    ->execute();
foreach ($rs as $user) {
    echo $user->name, "\n";
    echo '</br>';
}


$conditions = "name = :name: AND phone = ?1";

$parameters = array(
    "name" => "phalcon",
    1      => "13011111111"
);

$rs = User::find(
    array(
        $conditions,
        "bind" => $parameters
    )
);

find函数是获取主键id等于传参的那一行数据,这里要注意phalcon所有的查询之后返回的都是一个对象,需要转换成数组需要使用toArray函数

   //查询出所有的记录
    $rs = User::find();
    var_dump($rs->toArray());

    echo '</br>';
    echo '</br>';
    //通过where条件进行查询匹配的
    $rs = User::find("name = 'phalcon'");
    echo "名称为'phalcon的用户有'", count($rs), "个\n</br>";

    echo '</br>';
    // 获取名称为phalcon的用户并且通过phone排序
    $rs = User::find(array(
        "name = 'phalcon'",
        "order" => "phone"
    ));
    foreach ($rs as $user) {
        echo $user->name, "\n";
        echo $user->phone, "\n";
        echo '</br>';
    }
    echo '</br>';

    // 获取通过name排序的前100条数据
    $rs = User::find(array(
        "order" => "name",
        "limit" => 100
    ));
    foreach ($rs as $user) {
        echo $user->name, "\n";
        echo '</br>';
    }

    //通过findFirst可以获取第一条符合查询条件的结果 可以和find一样加入条件
    $rs = User::findFirst();
    echo "第一个用户的名称为 ", $rs->name, "\n";

修改


public function updateAction() {

    $User       = new  User();
    $User->id   = 1;
    $User->name = "test";
    //执行操作
    $ret = $User->save();

    //对结果进行验证
    if ($ret) {
        echo "修改数据成功";
    } else {
        //如果插入失败处理打印报错信息
        echo "修改数据库失败了";
        foreach ($User->getMessages() as $message) {
            echo $message->getMessage(), "<br/>";
        }
    }
}

删除


public function deleteAction() {

    $User       = new  User();
    $User->id   = 1;
    //执行操作
    $ret = $User->delete();

    //对结果进行验证
    if ($ret) {
        echo "删除数据成功";
    } else {
        //如果插入失败处理打印报错信息
        echo "删除数据库失败了";
        foreach ($User->getMessages() as $message) {
            echo $message->getMessage(), "<br/>";
        }
    }
}

count-max-min-average


$count = User::count();
echo '</br>' . $count;

$count = User::count(array(
    "distinct" => "name"
));
echo '</br>' . $count;

$sum = User::sum(array(
    "column" => "phone"
));
echo '</br>' . $sum;

$sum = User::sum(
    array(
        "column"     => "phone",
        "conditions" => "name = 'phalcon'"
    )
);
echo '</br>' . $sum;

$average = User::average(
    array(
        "column" => "phone"
    )
);
echo '</br>' . $average;

$max = User::maximum(
    array(
        "column" => "phone"
    )
);
echo '</br>' . $max;

$min = User::minimum(
    array(
        "column" => "phone"
    )
);
echo '</br>' . $min;

映射数据库


class Developer extends Model
{
    public function getSource()
    {
        return "user";
    }
}
public function initialize()
{
    $this->setSource("the_robots");
}


添加单独初始化


public function onConstruct()
{
    //需要做的事情
}



    //public 设置需要写入的数据
    $User->name   = "phalcon";
    $User->phone  = "13011111111";
    $User->passwd = "passwd";


    //producted设置需要写入的数据
    $User->getName("phalcon");
    $User->setPhone("13011111111");
    $User->setPasswd("passwd");


public function getId() {

    return $this->id;
}

public function setName($name) {

    if (strlen($name) < 10) {
        throw new \InvalidArgumentException('The name is too short');
    }
    $this->name = $name;
}

public function getName() {

    return $this->name;
}

public function setPhone($phone) {

    if (strlen($phone) != 11) {
        throw new \InvalidArgumentException('用户电话号码不足11位或超过');
    }
    $this->phone = $phone;
}

public function getPhone() {

    return (double) $this->phone;
}

public function setPasswd($passwd) {

    if (strlen($passwd) <= 5) {
        throw new \InvalidArgumentException('用户密码长度不足5位');
    }
    $this->passwd = $passwd;
}

public function getPasswd() {

    return $this->passwd;
}

VIEW


$this->view->setTemplateBefore('common')和$this->view->setTemplateAfter('common')可以控制渲染顺序

选择视图


public function indexAction($Id) {
    $this->view->pick("Index/index");
    $this->view->Id = $Id;
}







过滤接收到的数据-组件

<?php

use Phalcon\Filter;
$filter = new Filter();

// 返回 "someone@example.com"
$filter->sanitize("some(one)@exa\mple.com", "email");

// 返回 "hello"
$filter->sanitize("hello<<", "string");

// 返回 "100019"
$filter->sanitize("!100a019", "int");

// 返回 "100019.01"
$filter->sanitize("!100a019.01a", "float");

public function saveAction()
    {
        // 获取post参数key为price的值并且使用double类型清理
        $price = $this->request->getPost("price", "double");

        // 获取post参数key为customerEmail的值并且使用email类型清理
        $email = $this->request->getPost("customerEmail", "email");
    }

过滤

use Phalcon\Filter;

$filter = new Filter();

// 返回 "Hello"
$filter->sanitize("<h1>Hello</h1>", "striptags");

// 返回 "Hello"
$filter->sanitize("  Hello   ", "trim");

<?php

use Phalcon\Filter;

class IPv4Filter
{
    public function filter($value)
    {
        return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
    }
}

$filter = new Filter();

// 使用对象
$filter->add('ipv4', new IPv4Filter());

// 利用"ipv4"过滤器清理
$filteredIp = $filter->sanitize("127.0.0.1", "ipv4");

<?php

use Phalcon\Filter;

class IPv4Filter
{
    public function filter($value)
    {
        return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
    }
}

$filter = new Filter();

// 使用对象
$filter->add('ipv4', new IPv4Filter());

// 利用"ipv4"过滤器清理
$filteredIp = $filter->sanitize("127.0.0.1", "ipv4");

phalcon拦截器-Validator

use Phalcon\Validation;
use Phalcon\Validation\Validator\Email;
use Phalcon\Validation\Validator\PresenceOf;

//初始化拦截器    
$validation = new Validation();
//定制你的拦截器规则,你需要验证的参数名比如:name,如果验证失败返回的message
$validation->add(
    'name', new PresenceOf(array(
    'message' => 'The name is required'
)))->add(
    'email', new PresenceOf(array(
    'message' => 'The e-mail is required'
)))->add(
    'email', new Email(array(
    'message' => 'The e-mail is not valid'
)));
//可以先过滤和清理请求参数
$validation->setFilters('name', 'trim');
$validation->setFilters('email', 'trim');
//注入参数可以放get可以放post可以限制数据源
$messages = $validation->validate($_REQUEST);
//判断有没有验证通过
if (count($messages)) {
    //如果通过打印报错信息
    foreach ($messages as $message) {
       echo $message, '<br>';
    }
    //结束执行后面的内容不再执行
    return;
}




版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享:
开发与运维
使用钉钉扫一扫加入圈子
+ 订阅

集结各类场景实战经验,助你开发运维畅行无忧

其他文章