PHP

浏览模式: 标准 | 列表 | 图文
好文推荐:PHP 杂谈《重构-改善既有代码的设计》之一 重新组织你的函数

好文推荐:PHP 杂谈《重构-改善既有代码的设计》之一 重新组织你的函数

不清楚这些博客是否还会连载,要知道连载这东西真的很耗精力,如果编辑器不好、如果不能自动保存,真的很可能是会失去连载的信息的。事实上,我就是因为这些问题放弃了一些文章的连载。辛苦写了上千字,结果因为编辑器的问题一下子消失了。

再过一段时间,我还是会准备将博客转换到typecho或者wordpress上,毕竟这两个博客软件都是可以支持xmlrpc来投稿的。这样,我就可以用第三方软件来投稿了。(firefox有插件,黑黑)

上链接了,不然会被人骂:(如果有更新,我这里也会同步更新链接,或者你就直接移步该作者的博客吧)

  1. PHP __autoload()方法真的影响性能吗?
  2. PHP 杂谈《重构-改善既有代码的设计》之一 重新组织你的函数
  3. PHP 杂谈《重构-改善既有代码的设计》之二 对象之间搬移特性
  4. PHP 杂谈《重构-改善既有代码的设计》之三 重新组织数据
  5. PHP 杂谈《重构-改善既有代码的设计》之四 简化条件表达式

暂时只有5篇关于PHP的,这还有一篇对话也可以看看:PHP 跟老大的对话。

因为其中这一段可以拿来共勉:

题外话:曾经我在离开一家工作一年的公司的时候!项目经理就跟我说你如果频繁跳槽,会对你的将来的发展是不利的,但是没有告诉我怎么不利?现在我有点明白了,因为我到过的公司很多技术过硬的人,都是在这个公司带过3年以上的人。我发现如果你在一家公司待很长时间,对你的技术提升是很有帮助的。
1》 不停的重构代码,提升你的代码质量。
我们开始进入公司的时候,一般都是公司急需赶个项目人手缺乏。等项目完成,一般都是1年左右。如果你在公司待足够长的时间,这个项目多多少少会跟你扯上边的,这时候,你会不停的翻看自己的代码,你也会不断的调整代码, 不断的重构你的代码——跟写文章一眼,你不停的看自己写过的文章,你会不停的做修改,越修改你的文章会越让你喜欢。
2》业务熟悉,能够更快更好的写出代码!——我个人比较喜欢“行云流水”似的感觉。
你如果在一个公司待了很长一段时间,那么你对这个领域是非常熟悉的。新需求上来,你会很快的知道怎么做代码架构,比如上面提到的,你就知道方法中,哪些代码部分可以抽出来,独立做成一个方法;你也会知道,将来什么地方会频繁修改的。——写代码,如行云流水般!
当然不一定就很有道理,但也不是完全没有道理

Yii框架中使用PDO时强制将表字段设为小写的BUG

Yii框架的使用者越来越多,虽然大多数情况下都能够被使用的很正常,但偶尔还是有一些小问题,比如mysql对库名和表名区分大小写,但字段名不区分;这个问题就给Yii框架使用者带来很大的烦恼,特别是这个表还不是自己设计的,只是你拿来使用的,这个郁闷程度啊。
于是有人提醒我,应该这么用,在components中的db数组里加入:attributes=>array(PDO::ATTR_CASE,PDO::CASE_LOWER),以达到强制小写的目的,嗯,想法是好的,但是gii没法用了,gii直接报错,排查了半天,发现可能是CMysqlSchema这个类中的createColumn方法导致的错误,因为当你设置为列名小写后,这个方法中的一些判断却还是用的大写,于是很多变量就找不到了,没有办法继续下一步操作,于是我改了一下这个函数:

/**
* Creates a table column.
* @param array $column column metadata
* @return CDbColumnSchema normalized column metadata
*/
protected function createColumn($column) {
$column = array_change_key_case($column, CASE_LOWER);
$c = new CMysqlColumnSchema;
$c->name = $this->getDbConnection()->getColumnCase() == PDO::CASE_LOWER
? strtolower($column['field'])
: ($this->getDbConnection()->getColumnCase() == PDO::CASE_UPPER ? strtoupper($column['field'])
: $column['field']);
$c->rawName = $this->quoteColumnName($c->name);
$c->allowNull = $column['null'] === 'YES';
$c->isPrimaryKey = strpos($column['key'], 'PRI') !== false;
$c->isForeignKey = false;
$c->init($column['type'], $column['default']);
$c->autoIncrement = strpos(strtolower($column['extra']), 'auto_increment') !== false;
return $c;
}


当然上面的代码很粗燥,我也只是先临时解决这个问题,这么写之后,马上gii就恢复正常了。黑黑

顺便再说一个技巧:以前用gii的时候,对于生成model类都是一个个的输入一个个的生成,总想着应该可以批量生成,但一直不知道如何操作,直到昨天在解决上面的问题时,发现原来在gii里有这样一段代码:

if($this->tableName[strlen($this->tableName)-1]==='*')

我晶啊,原来那个表名可以写成*啊,这样就是自动生成整个数据库的model了,哎,以前居然一直没在意。

ea4dfae6ee21d84e1aad71021d6fcd48

phpsqlsrv for windows

phpsqlsrv for windows

http://www.microsoft.com/download/en/confirmation.aspx?id=20098
其实在很久前就有这玩意了,现在居然是3.0了。在win下用这个驱动好啊,支持最新的Sql server,而且速度很快。同时,它居然还支持了PDO。。。

下载下来很方便,有几种不同的文件,根据你当前的情况来设置:
Perform the following steps to download and install the Microsoft Drivers for PHP for SQL Server:
1. Download SQLSRV30.EXE to a temporary directory
2. Run SQLSRV30.EXE
3. When prompted, enter the path to the PHP extensions directory
4. After extracting the files, read the Installation section of the SQLSRV30_Readme.htm file for next steps
看着readme一步一步就Over了。
08年的时候根据第一版的文件写过一个很简单的连接库,替换掉了当时discuz的sql连接库。现在。。。还是用PDO吧

Microsoft SQL Server Functions (PDO_SQLSRV)

Introduction

PDO_SQLSRV is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to MS SQL Server (starting with SQL Server 2005) and SQL Azure databases.

Installation

The PDO_SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The PDO_SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_pdo_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_pdo_sqlsrv_52_ts_vc6.dll file.

For more information about system requirements, see » SQLSRV System Requirements.

The PDO_SQLSRV extension is only compatible with PHP running on Windows. For Linux, see ODBC and » Microsoft's SQL Server ODBC Driver for Linux.

System Requirements (Microsoft Drivers for PHP for SQL Server)

SQL Server 2008 R2

To access data in a SQL Server 2005 or later database using the Microsoft Drivers for PHP for SQL Server, you must have the following components installed on your computer:

  • Supported operating systems for version 3.0 of the driver include:

    • Windows Server 2008 R2 SP1

      Windows Vista SP2

      Windows Server 2008 SP2

      Windows 7 SP1

  • Supported operating systems for version 2.0 of the driver include:

    • Supported operating systems for version 2.0 of the driver include:

    • Windows Server 2003 Service Pack 1

    • Windows XP Service Pack 3

    • Windows Vista Service Pack 1 or later

    • Windows Server 2008

    • Windows Server 2008 R2

    • Windows 7

  • PHP 5. For information about how to download and install the latest stable binaries, visit http://php.net.

    Microsoft Drivers for PHP for SQL Server, version 3.0 requires PHP 5.3.0 or later. If possible, use PHP 5.3.6, or later. The version 2.0 driver works with PHP 5.2.4 or later. If possible, use PHP 5.2.13, or later.

  • A version of the driver file must be in your PHP extension directory. See Driver Versions later in this topic for information about the different driver files. See Loading the Microsoft Drivers for PHP for SQL Server for information on configuring the driver for the PHP runtime.

    (See The Data Center for the Microsoft Drivers for PHP for SQL Server for information on where to download the Microsoft Drivers for PHP for SQL Server.)

  • A Web server. Your Web server must be configured to run PHP. For information about hosting PHP applications with Internet Information Services (IIS) 6.0, see Using FastCGI to Host PHP Applications on IIS 6.0. For information about hosting PHP applications with IIS 7.0, see Using FastCGI to Host PHP Applications on IIS 7.0.

    The Microsoft Drivers for PHP for SQL Server has been tested using IIS 6 and IIS 7 with FastCGI.

  • The x86 version of SQL Server Native Client is required on the computer where PHP is running. If you are using a 64-bit operating system, the x86 version of SQL Server Native Client will be installed with the x64 version of SQL Server Native Client (do not install the x86 version of SQL Server Native Client on an x64 operating system).

    If you are using the SQLSRV driver, sqlsrv_client_info will return information about which version of SQL Server Native Client is being used by the Microsoft Drivers for PHP for SQL Server. If you are using the PDO_SQLSRV driver, you can use PDO::getAttribute to discover the version.

This section lists the drivers that are installed for version 2.0 and version 3.0 of the Microsoft Drivers for PHP for SQL Server. PHP version 5.2 is not supported in version 3.0 of the Microsoft Drivers for PHP for SQL Server.

Follow the installation instructions in Loading the Driver to configure the driver for use with the PHP runtime.

Microsoft Drivers 2.0 for PHP for SQL Server installs several versions of the driver:

Driver file

PHP version

Thread safe?

Use with PHP .dll

php_sqlsrv_53_nts_vc6.dll

php_pdo_sqlsrv_53_nts_vc6.dll

5.3

no

php5.dll

php_sqlsrv_53_nts_vc9.dll

php_pdo_sqlsrv_53_nts_vc9.dll

5.3

no

php5.dll

php_sqlsrv_53_ts_vc6.dll

php_pdo_sqlsrv_53_ts_vc6.dll

5.3

yes

php5ts.dll

php_sqlsrv_53_ts_vc9.dll

php_pdo_sqlsrv_53_ts_vc9.dll

5.3

yes

php5ts.dll

php_sqlsrv_52_nts_vc6.dll

php_pdo_sqlsrv_52_nts_vc6.dll

5.2

no

php5.dll

php_sqlsrv_52_ts_vc6.dll

php_pdo_sqlsrv_52_ts_vc6.dll

5.2

yes

php5ts.dll

If the name of the driver file contains "vc9", it should be used with a PHP version compiled with Visual C++ 9.0.

Microsoft Drivers 3.0 for PHP for SQL Server installs several versions of the driver:

Driver file

PHP version

Thread safe?

Use with PHP .dll

php_sqlsrv_53_nts.dll

php_pdo_sqlsrv_53_nts.dll

5.3

no

php5.dll

php_sqlsrv_53_ts.dll

php_pdo_sqlsrv_53_ts.dll

5.3

yes

php5ts.dll

phpQuery的一个小疑问。

phpQuery的一个小疑问。

最近在使用phpQuery处理xml的时候发生了一点小问题。由于xml还算是比较规范,但我又不想用simplexml_load_string,所以就偷懒用phpQuery处理了。
但在处理的时候发现一个问题,比如我要处理的内容是:

<title>揭秘日本巨型OLED地球仪:实时显示地球变化</title>
<link>http://news.dili360.com/gclw/xxjs/2012/0312/32136.shtml</link>
<description><a href='http://news.dili360.com/gclw/xxjs/2012/0312/32136.shtml'><img src='http://image.dili360.com/news/gclw/xxjs/2012/0312/36_5132136203_20120312094816.jpg' style='border: 1px solid #000000;'/></a> 新浪科技讯 北京时间3月12日消息,据国外媒体报道,如果你前往日本东京,别忘了去参观一下“未来科学馆”(Miraikan),这里展示着一些最尖端的技术成就。就在去年年中,这里揭幕了全世界首个大型OLED显示屏,直径超过19英尺(约合5.8米)。尽管名叫“Geo-Cosmos”,但这并非一般的地球仪,它几乎能实时显示我们这颗星球上正在发生的一切!全球各地的科学家和研究机构将数据发送给Geo-Cosmos,后者将其呈现给观众。 这..</description>
<category>中国国家地理网地理资讯频道</category>
<author>dili360.com</author>
<pubdate>2012-03-12 09:48:16</pubdate>

请看加红的那一段。
当我用phpQuery处理完后,发现,右边的</link>不见了。其他元素都正常。我的心一下子就碎了。
开始以为页面有问题,但怎么处理都是这样,最终只能将link换成了url来 进行处理。说实话,心是哇凉哇凉的。。

但是,同事在win下面就没有这个问题,我在ubuntu下就有这个问题。(我现在不知道是否我的PHP版本有问题,还是平台的问题,也没有心思深究了)【同事是5.3.9,我是5.3.6】,

PHP 5.4 更新

PHP 5.4 更新

有些更新由于没有仔细看,结果就出错了,所以,还是COPY出来,以后查起来方便一点,顺便告诉自己,session函数有部分不能用了。。。

Backward Incompatible Changes

Although most existing PHP 5 code should work without changes, please take note of some backward incompatible changes:

  • Safe mode is no longer supported. Any applications that rely on safe mode may need adjustment, in terms of security.【如果有运行在安全模式下的程序,要发了。。。。】
  • Magic quotes has been removed. Applications relying on this feature may need to be updated, to avoid security issues. get_magic_quotes_gpc() and get_magic_quotes_runtime() now always return FALSE. 【这个是早就知道了】set_magic_quotes_runtime() raises an E_CORE_ERROR level error.
  • The register_globals and register_long_arrays php.ini directives have been removed.【第二个函数没用过,现在也不用了】
  • Call-time pass by reference has been removed.【早就不用了。。。。】
  • The break and continue statements no longer accept variable arguments (e.g., break 1 + foo() * $bar;). Static arguments still work, such as break 2;.【HOHO,这个嘛。。。不影响 】
  • In the date and time extension, the timezone can no longer be set using the TZ environment variable. Instead you have to specify a timezone using the date.timezone php.ini option or date_default_timezone_set() function. PHP will no longer attempt to guess the timezone, and will instead fall back to "UTC" and issue a E_WARNING.【这个可能需要注意了。。。。】
  • Non-numeric string offsets - e.g. $a['foo'] where $a is a string - now return false on isset() and true on empty(), and produce a E_WARNING if you try to use them. Offsets of types double, bool and null produce a E_NOTICE. Numeric strings (e.g. $a['2']) still work as before. Note that offsets like '12.3' and '5 foobar' are considered non-numeric and produce a E_WARNING, but are converted to 12 and 5 respectively, for backward compatibility reasons.【。。。。。会有意外了】
  • Converting an array to a string will now generate an E_NOTICE level error, but the result of the cast will still be the string "Array".
  • Turning NULL, FALSE, or an empty string into an object by adding a property will now emit an E_WARNING level error, instead of E_STRICT.
  • Parameter names that shadow super globals now cause a fatal error. This prohibits code like function foo($_GET, $_POST) {}.【难道有人这么用过???】
  • The Salsa10 and Salsa20 hash algorithms have been removed.
  • array_combine() now returns array() instead of FALSE when two empty arrays are provided as parameters.
  • If you use htmlentities() with asian character sets, it works like htmlspecialchars() - this has always been the case in previous versions of PHP, but now an E_STRICT level error is emitted.

The following keywords are now reserved, and may not be used as names by functions, classes, etc.

The following functions have been removed from PHP:

升级sablog 2.0失败

升级sablog 2.0失败

纠结了很久,还是失败了。
看了一下出问题的step,发现是drop table的问题,我开始以为是我的权限有问题。但。。。我设置为ROOT也没用。所以暂时不升级了。真纠结啊

---------
顺便:
从PHP5.4开始,session_register函数禁用了。所以,如果还在使用Sablog1.6的人,记着。。。seccode.php中,这一行注释掉,否则。。。验证码就出不来了。
---------
由于升级到5.4后,默认display_error为OFF,所以很多错误 都显示不出来,排查了好久才解决这个问题啊。

开始启用Yii的redis插件

开始启用Yii的redis插件

该死的command+左箭头。。。写了十分钟的东西全没了。
-------重新开始-----
由于目前的一个项目涉及到的数据库需要跨库跨表操作,而且该库会被频繁的插入、更新、删除,所以相对速度会较慢。但查询量又较大,在一台服务器的情况下,怎么办?分端口主从吧,意义不大,因为某些操作会导致CPU瞬间100%。
这时候我想到了key/value的数据库,想用它来做中间处理,比如大量的内容先经过它,再真正入库,毕竟我不需要过分实时,也不涉及到金钱交易。于是乎就在redis和mongo中间犹豫了。
在这期间咨询了三个人:老王(基于博客http://huoding.com/2012/02/29/146,基于Redis消息系统实现);11爷(redis有pub/sub功能);烂桔(mongo不太适用于单机,redis有内存模式)

基于上述原因,于是选择了redis,那么就开始我的Redis之旅吧
1、安装 Redis ,参考:http://library.linode.com/databases/redis/ubuntu-10.10-maverick(如果我没记错,这应该是11爷推荐的地址,他本来推荐的是Centos下的,但我用的是ubuntu,所以就参考这个了)
先来三个常规操作

apt-get update
apt-get upgrade
apt-get install build-essential

完事之后,接着:

cd /opt/
mkdir /opt/redis
wget http://redis.googlecode.com/files/redis-2.4.8.tar.gz
tar -zxvf /opt/redis-2.4.8.tar.gz
cd /opt/redis-2.4.8/
make

make完后做如下操作,将一些配置文件拷贝到/opt/redis目录下:

cp /opt/redis-2.4.8/redis.conf /opt/redis/redis.conf.default
cp /opt/redis-2.4.8/src/redis-benchmark /opt/redis/
cp /opt/redis-2.4.8/src/redis-cli /opt/redis/
cp /opt/redis-2.4.8/src/redis-server /opt/redis/
cp /opt/redis-2.4.8/src/redis-check-aof /opt/redis/
cp /opt/redis-2.4.8/src/redis-check-dump /opt/redis/
cp /opt/redis/redis.conf.default /opt/redis/redis.conf

接着,更新/opt/redis/redis.conf:

daemonize yes
pidfile /var/run/redis.pid
logfile /var/log/redis.log

port 6379
bind 127.0.0.1
timeout 300

loglevel notice

## Default configuration options
databases 16

save 900 1
save 300 10
save 60 10000

rdbcompression yes
dbfilename dump.rdb

dir /opt/redis/
appendonly no

以上是linode里的配置,你可以参考一下做处理。大部分都一样,但timeout/loglevel/dir这三个参数不太一样。可以看着注释改一下。 linode 中有一个:glueoutputbuf yes ,这个在2.4.8下面会出错,所以我就没有启用它。
接着是加入启用脚本,既然linode有配置参考,那么它就有启动脚本,默认redis是没有给你这些启动脚本的,所以偷懒一下吧,下载linode的脚本:

cd /opt/
wget -O init-deb.sh http://library.linode.com/assets/630-redis-init-deb.sh
adduser --system --no-create-home --disabled-login --disabled-password --group redis
mv /opt/init-deb.sh /etc/init.d/redis
chmod +x /etc/init.d/redis
chown -R redis:redis /opt/redis
touch /var/log/redis.log
chown redis:redis /var/log/redis.log
update-rc.d -f redis defaults

在这一步之后,你就可以直接用/etc/init.d/redis 来 start和stop redis服务了。

2、安装phpredis(https://github.com/nicolasff/phpredis)
在安装之前,先看readme:https://github.com/nicolasff/phpredis/blob/master/README.markdown
看完readme之后你会发现,原来一切是这样的简单啊
OK,先wget 回源代码,然后tar解开目录。。
接着3步搞定:

phpize
./configure
make && make install

速度超快,make install后,会告诉你redis.so生成在哪里,你将这extension=redis.so,加入到你的php.ini中即可。

3、下载YiiRedis项目。(由于我是用Yii的,所以直接用这个插件了,否则,还是参考一下phpredis的一些用法)
同样,在这里有readme:https://github.com/phpnode/YiiRedis/blob/master/README.md
项目地址:https://github.com/phpnode/YiiRedis(请自行下载)
使用方法也很简单,和db一样,在components下加一个组件:

"components" => array(
"redis" => array(
"class" => "packages.redis.ARedisConnection",
"hostname" => "localhost",
"port" => 6379
),
//...
),

加完它之后就可以写上一段测试代码了:

Yii::import("ext.yiiredis.*");
$list = new ARedisList("aNameForYourListGoesHere");
$list->add("cats");
$list->add("dogs");
$list->add("goods");
foreach($list as $i => $val) {
print_r($val) ;
echo "<br />";
}
$list->clear(); // delete the list

直接输出在浏览器中。是不是很HIGH?
------
OK,就介绍到这里,请试用吧。

=------

备注:

$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE); // don't serialize data
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); // use built-in serialize/unserialize
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY); // use igBinary serialize/unserialize

$redis->setOption(Redis::OPT_PREFIX, 'myAppName:'); // use custom prefix on all keys

由于redis默认不做序列化,因此如果要存储PHP的数据,如:数组、对象,那就必须用第二个setOption进行设置,以便 让数据自动序列化

Yii Framework DB 中的一些参数

Yii Framework DB 中的一些参数

Yii的AR一直在被使用,当然,偶尔也只是看看其中的参数,都是直接把main.php中的数据注释掉就完事了
但事实上我们都忽略了一点点现实,那就是默认参数是没有什么性能提升的。

1、'schemaCachingDuration'=>3600,
这个在默认参数中是不存在的,如果你的表结构不太变动,完全可以不需要每次都show columns,show create table之类的。加上这个参数,可以将表结构缓存一小时(嗯,前提是,你配置了cache组件)

2、emulatePrepare=true ,这个是默认里面就带有的,它有什么用呢?
官方是这样说的:whether to turn on prepare emulation. Defaults to false, meaning PDO will use the native prepare support if available. For some databases (such as MySQL), this may need to be set true so that PDO can emulate the prepare support to bypass the buggy native prepare support. Note, this property is only effective for PHP 5.1.3 or above.
好吧,为了以防万一,还是打开算了

3、'enableProfiling'=>true
如果你想优化代码的话,可以尝试设置为true看看。官方在guide里说:By setting CDbConnection::enableProfiling to be true in the application configuration, every SQL statement being executed will be profiled. The results can be readily displayed using the aforementioned CProfileLogRoute, which can show us how much time is spent in executing what SQL statement. We can also call CDbConnection::getStats() to retrieve the total number SQL statements executed and their total execution time.

4、 'enableParamLogging'=>true,
这个就相对比较简单了,如果你设置为True,你在log中,就可以看到你的每次参数的参数是什么了,而不是:y01:y02这样的顺序变量。

5、tablePrefix = "xxx",这没什么好解释的。。。

6、charset="xxx" ,也没有什么好解释的,utf-8的话,中间的减号不要。。


这些都是常用的。。所以列出来