PHP Framework

浏览模式: 标准 | 列表 | 图文
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一样,不审会有一些其他的构思,需要期待了

15d99896386935366836aea39dc426c4

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

Yii的config配置的一些记录

Yii的config配置的一些记录

用YII开发的时候,由于会用到gii之类的工具,所以assets目录,仿佛就一定会需要存在了,但是assets这个目录名,会可能与我们自己的一些image,css之类的目录存在冲突(我是指目录太多了,不易管理,虽然这个目录似乎也不需要管理)
这时候,我们可以通过更改config来设置。
在config的components里加入:

'assetManager'=>array(
'basePath' => 'xxxxxx/xxx'
)

OK,我就这样把它与我存放image/css/js的目录合并在一起了。

模版,如果不想过多的折腾,我想,官方推荐的prado这样的伪PHP模版其实也不错,最起码常用的操作都封装了,也不用担心与其他的模版是否会存在这样那样的冲突,最起码他们的整合应该算是最好的。所以。。。加上:

'viewRenderer' => array(
'class' => 'CPradoViewRenderer',
),

不用过多的担心效率,它也是编译到runtime目录下执行的。。。

params,这个嘛。。。直接引用文件吧,其实在自动生成的代码里,就是这样配置的,直接引用文件有一个好处就是,你可以把系统的配置信息扔到一个文件里,然后让params来加载。就方便很多了。

Yii ClinkPager 郁闷

开发的时候,分页用了CLinkPager,然而在某一个页面的时候,page一直在变,但是下面的分类中的当前页永远在1上,不随着页码的变化而变化。
开始的时候以为是分页程序有问题,仔细对应了一下,发现分页的数据是正确的。
排查了半个多小时,突然想起,会不会$_GET['page']被unset了?
找了一下页面,最后在模版页里居然真的发现了unset($_GET['page']),当时我就傻眼了。
顺便再上一个option的onchange切换函数。很烂,只求先解决问题。。。。

function urlchange(field,value) {
var href= location.href;
var regex = new RegExp(field+"=[\-|0-9]{0,}");
if(href.indexOf(field)!=-1){
location.href = href.replace(regex,field+"="+value);
}else{
location.href = href + "&"+field+"="+value;
}
}

用法就是<select onchange="urlchange('page',this.value)"><option value='1'>第一页</option><option value='2'>第二页</option><option value='10'>第十页</option></select>

c7b4d5bbb79b3040393cc7c1227352f5

Yii Rewrite中遇到的困惑

Yii Rewrite中遇到的困惑

用Yii开发的时候,总是会有涉及到rewrite,否则,网址里一堆 index.php?r=xxxx那就真的太长了。

关于rewrite,可以参考官方的guide,不过上面只有针对apache的htaccess配置。如果是nginx,你还可以搜索一下官方的wiki,有介绍nginx的配置的。只是官方上面用的方法是try_file,只针对高版本的。如果是低版本还是得用 if (!e $request_filename)这类的【更多设置请搜索google】我这里不详细说了。

今天在用官方推出的这一种rewrite功能【Parameterizing Hostnames 】的时候,出了点问题,该功能是:

Parameterizing Hostnames

Starting from version 1.0.11, it is also possible to include hostname into the rules for parsing and creating URLs. One may extract part of the hostname to be a GET parameter. For example, the URL http://admin.example.com/en/profile may be parsed into GET parameters user=admin and lang=en. On the other hand, rules with hostname may also be used to create URLs with paratermized hostnames.

In order to use parameterized hostnames, simply declare URL rules with host info, e.g.:

array(
'http://<user:\w+>.example.com/<lang:\w+>/profile' => 'user/profile',
)

The above example says that the first segment in the hostname should be treated as user parameter while the first segment in the path info should be lang parameter. The rule corresponds to the user/profile route.

Note that CUrlManager::showScriptName will not take effect when a URL is being created using a rule with parameterized hostname.

Also note that the rule with parameterized hostname should NOT contain the sub-folder if the application is under a sub-folder of the Web root. For example, if the application is under http://www.example.com/sandbox/blog, then we should still use the same URL rule as described above without the sub-folder sandbox/blog.

我在rules里写上了 "http://user.xxx.com/<_c:\w+>/<_a:\w+>"=>"user/<_c>/<_a>/"

然后发现访问 http://user.xxx.com/aaa/bbb/id/1的时候出现了404错误,找问题死活找不到在哪里。再转过头去看了很多其他的配置,发现都不正常。

然后,我尝试访问默认页,即没有参数的:http://user.xxx.com/default/index,咦,居然正常了。。但问题随之而来,其他链接都不正常,经过不停的测试测试再测试。最终发现,把""user/<_c>/<_a>/" 中最后一个 / 去掉就正常了。

那么,'<_m:\w+>/<_c:\w+>/<_a:\w+>' => '<_m>/<_c>/<_a>/' 和 '<_m:\w+>/<_c:\w+>/<_a:\w+>' => '<_m>/<_c>/<_a>' 的区别是什么呢?

仔细看了一下生成的链接,如果用第二种的时候,如果有多个参数,就转为 m/c/a?a=b&c=d 而如果用第一种就是生成 m/c/a/a/b/c/d 。这时候,系统可能会识别不出我这种用二级域名做rewrite的方式。于是,我去掉了最后一个“/”,一切都正常了。

期间,HM和Horadric.Cube多次对我帮助,告诉我不同的nginx参数的配置。灰常感谢。

Yii 错误操作引起的问题

Yii 错误操作引起的问题

在YII项目实施过程中,遇到一个问题,即,只在某一个module里需要获取IP的来源,并判断具体来自于何处。

默认在yii里取得客户端IP只有一个简单的方法,来自于ChttpRequest类,只是这里只有一个判断,即Remote_addr,而这个,一般来说是不准的,因此,我直接COPY了康盛的IP来源判断。

然后通过那个比较出名的iplocation类读取wry.dat,来获取IP的定位(iplocation仿佛是几年前王总写的还是andot写的?用来分析纯真IP库的。说起这个wry.dat,事实上,它的来源还真是要从以前的一款软件:追捕说起,但那个年代远了,早就消失在历史的长河中了。)

好吧,上面就是我要说的背景,于是,我认为,既然要在module里获取,那么我就在module的init方法里直接实现了吧。

然后,我把具体的获取IP,并且分析IP来源,并到数据库查询以获取Area_id的代码扔在了module 的 init 方法里,然后运行一看,直接502 bad gateway出现了。折腾了好久,发现都一直是502。

但是测试了一下,把这些代码COPY到Controller的action里面,又十分正常(因为没空研究module的实现),于是就把代码COPY到module的beforeAction方法中了。

然后问题解决。(没仔细想为什么,只是纯粹一个记录,让自己知道,尽量不要在init里写上一大堆实现代码。。。)

Yii 一行代码,为模块绑定子域名

Yii 一行代码,为模块绑定子域名

我在dongbeta的网站上看到了这个东西,突然觉得原来子域名真的很简单,原来我还在想,如何绑定一些子域名的事情呢。

看一下原文吧,然后说明一下,官方的手册中其实已经有类似的介绍了,只是目前这一部分还是英文版的,这可能和这个功能是最新刚加入的关吧。。来源网址为:http://dongbeta.com/view/655

--start--

Yii强大的路由功能配置相当灵活,特别是增加了参数主机名路由功能之后更是可以灵活控制域名。感觉每一次提出一个提议,Yii的开发者qiang如果采纳,就会给出一个我没有想到却更加强大的解决方案。这次就是这样。

下面就是可以将所有子域名都转化为模块的路由规则,来自Yii官方论坛的一个帖子:

'http://<_m:\w+>.xxx.com<_q:.*>/*'=>'<_m><_q>',
规则写在main.php中的组件配置数组里面:
'urlManager'=>array(
'urlFormat'=>'path',
'showScriptName' => false,
'rules’=>array(
'http://<_m:\w+>.xxx.com<_q:.*>/*'=>'<_m><_q>',
)
),
如果仅仅是一个模块(假设是user)需要绑定子域名,可以这样写规则:
'http://user.xxx.com<_q:.*>/*'=>'user<_q>',
如果是若干模块需要绑定子域名,可以这样写:
'http://<_m:(user|admin|photo)>.xxx.com<_q:.*>/*'=>'<_m><_q>',

在使用的时候我注意到,如果是www开头的网址也会被转向到www模块,那么你可以使用(A|B|C)这样的规则选择要启用的模块,或者使用正则来滤掉www。

另外在路由规则里面,如果某一条匹配,则不会向下进行匹配。这是需要注意的,但是正是这样,路由才更高效,更灵活。

官方的URL管理说明文档:http://www.yiiframework.com/doc/guide/topics.url ,中文的我还没有翻译,等翻译之后,会发布到官方网站。

--EOF--

正如上面作者所说,官方这一段确实还是英文,可以看这里:http://www.yiiframework.com/doc/guide/1.1/zh_cn/topics.url,不过也很容易理解

以下来自官方:

Parameterizing Hostnames

Starting from version 1.0.11, it is also possible to include hostname into the rules for parsing and creating URLs. One may extract part of the hostname to be a GET parameter. For example, the URL http://admin.example.com/en/profile may be parsed into GET parameters user=admin and lang=en. On the other hand, rules with hostname may also be used to create URLs with paratermized hostnames.

In order to use parameterized hostnames, simply declare URL rules with host info, e.g.:

array(
'http://<user:\w+>.example.com/<lang:\w+>/profile' => 'user/profile',
)

The above example says that the first segment in the hostname should be treated as user parameter while the first segment in the path info should be lang parameter. The rule corresponds to the user/profile route.

Note that CUrlManager::showScriptName will not take effect when a URL is being created using a rule with parameterized hostname.

Also note that the rule with parameterized hostname should NOT contain the sub-folder if the application is under a sub-folder of the Web root. For example, if the application is under http://www.example.com/sandbox/blog, then we should still use the same URL rule as described above without the sub-folder sandbox/blog.

yii-1.1.0-validator-cheatsheet

官方的GUIDE里,对于validator的介绍太少了,只有这么一段 :

7. Validator(验证)

Validator需继承CValidator和实现CValidator::validateAttribute方法。

class MyValidator extends CValidator
{
protected function validateAttribute($model,$attribute)
{
$value=$model->$attribute;
if($value has error)
$model->addError($attribute,$errorMessage);
}
}

即使在这里,http://www.yiiframework.com/doc/api/1.1/CValidator,介绍的也不是特别的多,后来,找到了这个cheatsheet,感觉还不错,对应一下api的内容,感觉有点爽

感谢龙井的回复,使得我注意到了wiki,地址:http://www.yiiframework.com/wiki/56/reference-model-rules-validation/,可以关注一下下哦

d2c9b4bff7f5ee3917720732dbf46068

9329606bfa89ed00fde13bef5aaa8b18