PHP Framework

浏览模式: 标准 | 列表 | 图文
Yii数据库迁移工具

Yii数据库迁移工具

其实早就想写这样的文章来介绍这个玩意,不过一来项目中没有用到这个东西,二来官方的文档也是英文的,自己也没有仔细看就没有介绍。
官方的文档其实写的很详细了,不过因为真没用到它,也就没有发言权。
不过这两天在闲逛 ,倒是看到了一些文章:

  1. 小试Yii框架下的数据迁移功能
  2. yiichina的中文版介绍 :http://www.yiichina.com/api/CDbMigration
  3. 官方的手册:http://www.yiiframework.com/doc/guide/1.1/en/database.migration

这些文章还是可以看看的,关键问题是这些配置改了之后,难道会自动更新model文件吗?哎。

烂桔回忆录:如何给字段默认赋值

烂桔回忆录:如何给字段默认赋值

以下内容都是烂桔童鞋的一些回忆录,嗯,针对Yii开发的回忆录,烂桔童鞋用yii应该也有2年多了吧。所以,有些小技巧啥的还是值得看看的:
好,现在又到了不定期yii小技巧分享的时间了,今天来说说如何给字段默认赋值
一般的表里都会有类似 created的字段,记录一个数据产生的时间戳,传统的做法都是在插入数据库的时候给这个字段赋值。
在yii框架呢?方法就很多了,比如在beforeValidae()里用 $this->created = time() 或者写个behavoir。
但我要说,这种做法弱爆了,其实有更简单的办法。
yii默认提供了一个叫 default的验证器,意思就是给字段默认赋值,那么现在重点来了,怎么是使用呢?以created字段举例:
array('created', 'default', 'value' => time(), 'setOnEmpty' => false, 'on' => 'insert'),

在model的rules()方法里,加上上面那行即可,这样,created字段就会在插入新数据的时候自动被赋值一个时间戳了。

同理也可以用在updated字段,修改 'on' => 'update' 即可

当然,这个不仅仅可以用来记录时间戳,我们操作后台的时间,往往要记录一些最后操作某条记录的某个人,同样也可以直接在这里做,非常方便,不是吗?
------------------
正在征集烂桔更多的回忆录。

YII中的CComponent,CEvent与Behavior及CActiveRecordBehavior

YII中的CComponent,CEvent与Behavior及CActiveRecordBehavior

上一篇文章我介绍的是官方的event和behavior的文章,这一篇是来自个人博客。
嗯,本来只是放在read it later做备份的,不料今天打开的时候发现,这篇文章已经不见了。该博客重新创建,原来的数据都没有了。所幸,我曾用read it later处理过纯文本模式,因此,我将它备份下来,以防哪天read it later也崩了。
ok,上原文链接。靠,原文打不开了,还是上这家网站的地址吧。。。http://www.trailroom.com/
内容其实这样的:

YII中的CComponent,CEvent与Behavior及CActiveRecordBehavior个人理解
这一块教程少,今天个人理解了下,写了个小例子,有助于理解

完成如下功能,一个JTool类,继承CComponent,当其长度改变时,调用事件,输出”change me”.
JTool.php在protected/components 下:

<?php
class JTool extends CComponent{
private $_width;
public function getWidth(){
return $this->_width ? $this->_width : 1;
}

public function setWidth($width){
if($this->hasEventHandler(‘onChange’)){
$this->onChange(new CEvent());
}
$this->_width = $width;
}

public function onChange($event){
$this->raiseEvent(‘onChange’, $event);
}

OK,功能已经实现了,找个控制器,执行

现在我们想给JTool添加一个功能,返回长度的100倍,我们可以继承JTool.php写一个方法

[。。。TEXT后,这一段内容消失了]
OK,功能实现了,这个执行就简单了new JToolSub调用方法即可

上边的这两种办法,就是仅完成功能,下边演示Behavior及events来实现

如何用Behavior来实现上边的增加一个方法,返回长度的100倍的功能呢?
写类JBe
JBe.php在protected/behavior 下:

class JBe extends CBehavior{

public function get100width(){
return $this->Owner->width*100;
}
}

OK,功能已经实现了,找个控制器,执行

如何用Behavior实现JTool中的长度改变时,调用一个事件的功能呢?
写类JBe:

class JBe extends CBehavior{
public function events(){
return array_merge(parent::events(),array(
‘onChange’=>’change’,
));
}

public function change(){
echo ‘changed’;
}

public function get100width(){
return $this->Owner->width*100;
}
}

OK,功能实现随便找个控制器,执行

这里的要点是events方法
返回的数组array(‘onChange’=>’change’)定义了事件(event)和对应的事件处理方法(event hander)

事件是是Compents(JTool中)定义的,即JTool中的onChange
处理方法同由Behavior(JBe中)类定义的,即JBe中的change

这样子再看CActiveRecordBehavior,其是绑定给CActiveRecord 这个组件的,绑定方法重写behaviors()
CActiveRecordBehavior中的events() 方法返回事件及事处理函数的对应,如:
‘onBeforeSave’=>’beforeSave’

即组件CActiveRecord中的onBeforeSave这个事件对应的处理函数是
CActiveRecordBehavior中的beforeSave方法

这样子CActiveRecord在调用save()时,触发事件onBeforeSave,调用CActiveRecordBehavior对应的处理函数beforeSave
我们只要写一个CActiveRecordBehavior的子类,重写其中的beforeSave,执行一些操作,然后给CActiveRecord绑定即可

我还有个疑问,在继承CBehavior时,是不是一定要让方法events()反回那个对应关系的数组,如果这里为空,没有默认的对应关系?

---------

虽然TEXT保留了大部分内容,但还是有一小部分不见了。真可惜

Yii 官方关于event和behaviors的文章

Yii 官方关于event和behaviors的文章

本文内容来自官方的wiki,一来是做备份,二来自己查询起来也会快一点,毕竟yiiframework官网经常抽风,当然它的抽风不是因为自己,而是因为GFW,说来也可怜,好象很多技术网站都被墙了。
不过想想也正常,如果一个搞技术的,连翻墙也不会,还搞个毛技术啊。
OK,上正菜:http://www.yiiframework.com/wiki/44/behaviors-events/#hh1

These features provide endless possibilities and unbelievable flexibility, but as current documentation does not give more than a few examples, it might be difficult to fully understand their internals and requirements.

It should be noted that they do mostly the same thing. You can attach behaviors and event handlers to components to modify the components' behavior.

Events

It is useful when you want to interrupt the normal application flow without extending base classes.

For example, enabling gzip compression on the output could be done via extending CWebApplication. But because there are entry points for event handlers, one can do this:

Yii::app()->onbeginRequest = create_function('$event', 'return ob_start("ob_gzhandler");'),
Yii::app()->onendRequest = create_function('$event', 'return ob_end_flush();'),

You can create an event handler -- which is simply a method in some class with a specific signature -- and attach it to the event of an object. You can add as many event handlers as you wish, from as many objects as you wish. If the event handler is, effectively static, then you can create the object as you assign it:

$test_comp->onSomethingGoesOn = array(new SomeClass, 'eventHandler1');
$test_comp->onSomethingGoesOn = array(new SomeOtherClass, 'eventHandler2');
$test_comp->onSomethingGoesOn = array(new YetAnotherClass, 'eventHandler3');

As long as you have a handle on the object, then you can add an event handler to it.

At some point, you can then raise the event with something like one of these:

$test_comp->onSomethingGoesOn(new CEvent($this));
$test_comp->onSomethingGoesOn(new CEvent());

So, basically, it allows you to build a list of function calls that can later be executed, in the order they were added. It can save you passing around a lot of object refs and building conditional code, since you can still raise the event, even if it doesn't do anything.

Behaviors

Behaviors are simply a way of adding methods to an object.

Take this scenario: You have 2 classes: MySuperClass1, MySuperClass2. There might be lots of methods from MySuperClass1 & 2 that you want in some new class, say MyBoringClass. Unfortunately, php does not allow for this:

class MyBoringClass extends MySuperClass1, MySuperClass2 {
}

This is where behaviors come in. Instead, you can go:

class MyBoringClass extends MySuperClass1 {
}

$classInstance = new MyBoringClass();
$classInstance->attachbehavior('uniqueName', new MySuperClass2);

Now $classInstance has all the methods from MySuperClass1 and MySuperClass2. Since MySuperClass2 is being used as a behavior, it has to extend CBehavior. The only caveat to this is an attached behavior cannot override any class methods of the component it is being attached to. If a method already exists, if it be from the original class or already added by a previously attached behavior, it will not be overwritten.

In an OO language like Ruby, it's quite possible to start with a completely empty object and simply build its behavior as you go along. Yii provides this behavior with a little magic. The key is that the class you wish to add the behavior from must extend Cbehavior.

class SomeClass extends CBehavior
{
public function add($x, $y) { return $x + $y; }
}

Then use with:

$test_comp = new TestComponent();
$test_comp->attachbehavior('blah', new SomeClass);
$test_comp->add(2, 5);

So, in this case, you are extending the functionality of an object with functionality of another object.

After studying this cookbook page you are encouraged to reread the corresponding guide page as it contains advanced information (for example, if you are familiar with interfaces, you might find it enough to implement IBehavior before extending CBehavior).

-------------

behavior和Event在model里用的会相对较多一点,不过,其他地方也可以一用。如果你真的不明白这一块的逻辑,那还是用其他方式替代吧。

Yii的Euploadify插件使用

Yii的Euploadify插件使用

Yii在自已内部已经实现了单文件上传和多文件上传的代码,只是很少会有人注意这些吧?
事实上更多时候,在多文件上传的时候,我们往往采用了swfupload来进行处理,但swfupload的参数太多了,用起来会非常复杂和痛苦。
所幸,有很多人知道这些事情,他们对swfupload重新进行了封装,并做了简化,比如这个uploadify。
官网上的例子也很简单,一个是立即上传,一个是自定义上传。其实 最主要的是uploadify的是它的回调函数很少也很方便,常用的就是onError,onCompleted,onAllCompleted,onSuccess之类的。
在Yii的Extension库中,也确实有一款插件叫做EUploadifyWidget。最面对一些变量进行了更多的封装,也就是让我们使用起来更方便。不过,在使用过程中,还是会发现,虽然它封装了很多操作,但其实有很多地方还是没有处理好,官网上的例子也没有处理好。
打开代码可以发现在run函里面有对options等的处理,根据实际需要进行调整就OK了(之所以要调整,其实也还有一个原因,是因为我在这次的项目中没有用到clientScript,而这个插件却用了它,所以我才会多进行了一些处理)
默认的路径还是需要做一些处理,路径中的baseURL是基于它自己的路径来处理的,还有需要更改的就是JS/CSS/swf等的路径需要注意,其他就Over了。

纯笔记

Yii CDbCriteria的常用方法

Yii CDbCriteria的常用方法

这是Yii CDbCriteria的一些笔记和常用用法:

$criteria = new CDbCriteria;
$criteria->addCondition("id=1"); //查询条件,即where id = 1
$criteria->addInCondition('id', array(1,2,3,4,5)); //代表where id IN (1,23,,4,5,);
$criteria->addNotInCondition('id', array(1,2,3,4,5));//与上面正好相法,是NOT IN
$criteria->addCondition('id=1','OR');//这是OR条件,多个条件的时候,该条件是OR而非AND
$criteria->addSearchCondition('name', '分类');//搜索条件,其实代表了。。where name like '%分类%'
$criteria->addBetweenCondition('id', 1, 4);//between 1 and 4

$criteria->compare('id', 1); //这个方法比较特殊,他会根据你的参数自动处理成addCondition或者addInCondition,
//即如果第二个参数是数组就会调用addInCondition
/**
* 传递变量
*/
$criteria->addCondition("id = :id");
$criteria->params[':id']=1;
/**
* 一些public vars
*/
$criteria->select = 'id,parentid,name'; //代表了要查询的字段,默认select='*';
$criteria->join = 'xxx'; //连接表
$criteria->with = 'xxx'; //调用relations
$criteria->limit = 10; //取1条数据,如果小于0,则不作处理
$criteria->offset = 1; //两条合并起来,则表示 limit 10 offset 1,或者代表了。limit 1,10
$criteria->order = 'xxx DESC,XXX ASC' ;//排序条件
$criteria->group = 'group 条件';
$criteria->having = 'having 条件 ';
$criteria->distinct = FALSE; //是否唯一查询

有需要用到的可以查看一下。。。

Yii笔记

Yii笔记

本文纯粹是笔记,记下来怕忘了
1、终止当前操作,一般情况下是用exit,但用了Exit后无法看到trace的内容。所以要采用Yii::app()->end();
2、createUrl和createAbsoluteUrl,这两个函数,如果需要宣传自己的网址和内容,还是用createAbsoluteUrl函数吧。里面带了全部路径,而CreateUrl只会显示/home/xxx这样的路径,不利于SEO
3、widget默认的render无法使用theme中的模版,于是写一个类继承自CWidget,然后所有的widget都继承这个类,比如我这样实现了。。

class Widget extends CWidget{
private static $_viewPaths;
/**
* 重写CWidget中的getViewPath
*/
public function getViewPath($checkTheme=false)
{
$className=get_class($this);
if(isset(self::$_viewPaths[$className]))
return self::$_viewPaths[$className];
else
{
if($checkTheme && ($theme=Yii::app()->getTheme())!==null){
return self::$_viewPaths[$className] = $theme->getBasePath().DIRECTORY_SEPARATOR."widgets"; //这是我自己的路径
}
$class=new ReflectionClass($className);
return self::$_viewPaths[$className]=dirname($class->getFileName()).DIRECTORY_SEPARATOR.'views';
}
}
}

覆写父类方法,使得getViewPath找到我指定的目录,我目录在themes/classic/下建了一个widgets的目录。这样的好处很多。。而且对于CSS和JS等路径都可以和标准视图一致

先写这么多。。。

怒了,QueryCache

怒了,QueryCache

怒了。真的怒了。。。。
前两天我还一直在想,怎么让yii实现查询的时候进行缓存,当时考虑在beforeFind和afterFind后做处理,但看了代码才发现beforeFind,如果不显式传入criteria,就没有办法把查询参数传递进去,那我就没有办法判断当前查询的param 是否被缓存了。AfterFind,倒是可以做处理,因为$event->sender或者$this中都已经有了结果集了。。。但没有办法判断是否缓存,查询完的缓存意义也就不大了。不是吗?

刚才无意中看了一下Yii 1.1.17的changelog,居然看到了这个:query-caching,当时我就震精了。http://www.yiiframework.com/doc/guide/1.1/en/caching.data#query-caching

好象这次1.1.17更新的几个功能都不错。。。查看这里:http://www.yiiframework.com/news/45/yii-php-framework-1-1-7-is-released/

  1. RESTful URL Support
  2. Query Caching
  3. Parameter Binding for Class-based Actions
  4. Seamless Client-side Validation
  5. Passing Parameters to Relational Named Scopes
  6. Using 'through' with HAS_MANY and HAS_ONE
  7. Using Transactions in DB Migration
  8. Registering and Using Custom Script Packages

好象,除了1、7我兴趣不是特别大,其它的几个都不错,原来的Actions中的Action无法绑定参数的,现在也直接可以用了,也就是说Action可以更容易的被移出。代码也更易分离了。4是客户端验证,原来还要在提交后到服务端验证,现在又方便一点了。。
其它的还是看看官方吧,不一定介绍了。

zend newsletter

收邮件的时候,收到了这封zend framework更新的信息,果然不出我所料,ZF要升级了,但究竟什么 时候能够出来,还要等啊

官方发出一条信息关于zend framework2模式的网络会议。它说:

Zend Framework 1 grew organically. An effort behind version 2.0 was to identify common themes and patterns, and to unify these in order to provide common low-level patterns to use everywhere.

Presented by Matthew Weier O'Phinney, this webinar will serve as an overview of these patterns, identifying them, and discussing the interfaces involved and the concrete use cases we plan to ship in ZF2. Matthew will also show how you might create your own implementations and slip-stream them into your application. Amongst the patterns discussed will be events, brokers, and dispatchers.
如果有兴趣的话还可以参加讨论。。。March 30,不知道讨论结束后会有怎么样的一个结果。比如2的模式是否与1一样,不审会有一些其他的构思,需要期待了
Yii:relations update(self::STAT)

Yii:relations update(self::STAT)

今天在群里有朋友问我yii的relations的问题,结果贴出来的代码居然是类似这样的:

function relations(){
return array(
'xx'=>array(self::STAT,'aa','aa_id')
);
}

我当时直接了当的对他说,错了,怎么可能会有self::STAT呢?只有has_many,has_one,belongs_to,many_many,stat是错的。结果他回答说我OUT了,STAT是新加入的。。。

于是欣欣然跑到YII的官网查看了一下GUIDE,果然在 Relational Active Record,一节中发现了这个Statistical Query。

官方怎么说来着?第一句就让我大吃一惊:

Note: Statistical query has been supported since version 1.0.4.

奇怪,以前怎么没注意?

Besides the relational query described above, Yii also supports the so-called statistical query (or aggregational query). It refers to retrieving the aggregational information about the related objects, such as the number of comments for each post, the average rating for each product, etc. Statistical query can only be performed for objects related in HAS_MANY (e.g. a post has many comments) or MANY_MANY (e.g. a post belongs to many categories and a category has many posts).

Performing statistical query is very similar to performing relation query as we described before. We first need to declare the statistical query in the relations() method of CActiveRecord like we do with relational query.

class Post extends CActiveRecord
{
public function relations()
{
return array(
'commentCount'=>array(self::STAT, 'Comment', 'post_id'),
'categoryCount'=>array(self::STAT, 'Category', 'post_category(post_id, category_id)'),
);
}
}

In the above, we declare two statistical queries: commentCount calculates the number of comments belonging to a post, and categoryCount calculates the number of categories that a post belongs to. Note that the relationship between Post and Comment is HAS_MANY, while the relationship between Post and Category is MANY_MANY (with the joining table post_category). As we can see, the declaration is very similar to those relations we described in earlier subsections. The only difference is that the relation type is STAT here.

With the above declaration, we can retrieve the number of comments for a post using the expression $post->commentCount. When we access this property for the first time, a SQL statement will be executed implicitly to retrieve the corresponding result. As we already know, this is the so-called lazy loading approach. We can also use the eager loading approach if we need to determine the comment count for multiple posts:

$posts=Post::model()->with('commentCount', 'categoryCount')->findAll();

The above statement will execute three SQLs to bring back all posts together with their comment counts and category counts. Using the lazy loading approach, we would end up with 2*N+1 SQL queries if there are N posts.

By default, a statistical query will calculate the COUNT expression (and thus the comment count and category count in the above example). We can customize it by specifying additional options when we declare it in relations(). The available options are summarized as below.

  • select: the statistical expression. Defaults to COUNT(*), meaning the count of child objects.

  • defaultValue: the value to be assigned to those records that do not receive a statistical query result. For example, if a post does not have any comments, its commentCount would receive this value. The default value for this option is 0.

  • condition: the WHERE clause. It defaults to empty.

  • params: the parameters to be bound to the generated SQL statement. This should be given as an array of name-value pairs.

  • order: the ORDER BY clause. It defaults to empty.

  • group: the GROUP BY clause. It defaults to empty.

  • having: the HAVING clause. It defaults to empty.

关键的是看最后这几个条件,可以让你知道这些参数如何配置。。。
官方的GUIDE地址:http://www.yiiframework.com/doc/guide/1.1/en/database.arr