PHP

浏览模式: 标准 | 列表 | 图文
Yii2 静态方法 中怎么触发事件

Yii2 静态方法 中怎么触发事件

在ActiveRecord的init中写了一个简单的事件触发:

public function init(){
$event = new XxxEvent();
$this->on(self::EVENT_AFTER_UPDATE,[$event,'doSomeThing']);
parent::init();
}

就是这么简单,然后在程序中有一段触发:

public static xxx(){
self::updateAllCounters([],[]);
}

然后发现,死活没有触发。追了一下代码发现,updateAllCounters没有从AR走,而是直接从db->createCommand()->execute走了

于是在下面加了一行:

self::trigger(self::EVENT_AFTER_UPDATE);

然而直接报错,说是trigger不支持静态调用,哦。。。trigger是非静态方法。

于是最后只能用万能的call_user_func_array的方法了:

call_user_func_array([new self,'trigger'],[self::EVENT_AFTER_UPDATE]);

有点贱,但总算实现了。

PHP 7 DomDocument not found

PHP 7 DomDocument not found

升到PHP7后,当用到DomDocument的时候,报错说class DomDocument not found。。。

用php -m|grep xml,可以看到libxml是被加载的。
根据官方文档:
This extension requires the libxml PHP extension. This means that passing in --enable-libxml is also required, although this is implicitly accomplished because libxml is enabled by default.
证明没有错。
事实上也有很多人遇到了这个问题,怎么破?对于我用apt-get install的人来说,实在太方便了。
直接:
apt-get install php7.0-xml
搞定。
参考:http://stackoverflow.com/questions/35668702/php-7-domdocument-not-found
去除内容中所有的多余的空格和空行

去除内容中所有的多余的空格和空行

去除内容中所有的多余的空格和空行

php > $str = "a b c d\n\ne f g \t 2";
php > echo preg_replace('/\s+/',' ',$str);
a b c d e f g 2
php > echo $str;
a b c d

e f g 2
php > echo preg_replace('/(\s)+/','$1',$str);
a b c d
e f g 2
应该没有写错
Editor.md 上传图片的注意事项

Editor.md 上传图片的注意事项

一般情况下,editor.md的上传图片功能已经够用了,提供了两种方式:本地上传和跨域上传,方式也很简单,跨域上传的话,则需要加callbackUrl的地址。参考:http://www.ipandao.com/editor.md/examples/image-upload.html 和 http://www.ipandao.com/editor.md/examples/image-cross-domain-upload.html。

不过我的问题和上面的不一样,因为我使用了PHP开发框架,那么在正常开发的过程中,表单提交都有csrf的验证。editor.md却没有这个功能,在官方的issue里有人提出了,可以通过设置uploadUrl来加入get参数。

嗯,理论上这样也OK。然而我使用的是YII2,在实际使用中,这个办法无效,原因是:

public function validateCsrfToken($token = null)
{
$method = $this->getMethod();
// only validate CSRF token on non-"safe" methods http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1
if (!$this->enableCsrfValidation || in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) {
return true;
}

$trueToken = $this->loadCsrfToken();

if ($token !== null) {
return $this->validateCsrfTokenInternal($token, $trueToken);
} else {
return $this->validateCsrfTokenInternal($this->getBodyParam($this->csrfParam), $trueToken)
|| $this->validateCsrfTokenInternal($this->getCsrfTokenFromHeader(), $trueToken);
}
}

看最后两个判断,只判断了POST和HEADER中有Csrf的情况,没有判断GET参数里的情况,如果你的项目已经趋向于稳定,不再随便升级Yii的版本,你可以在$this->validateCsrfTokenInternal($this->getBodyParam($this->csrfParam), $trueToken)加一行:

|| $this->validateCsrfTokenInternal($this->get($this->csrfParam),$trueToken)

即,允许从GET参数中获取 csrf的值。

然而,很多时间我们都会手贱去composer update,所以这个方法有点不太敢使用。最终,还是决定修改editor.md的插件,在image-dialog.js中加入几行:

if (settings.crossDomainUpload)
{
action += "&callback=" + settings.uploadCallbackURL + "&dialog_id=editormd-image-dialog-" + guid;
}
//在上面的if代码后先加入csrfToken的值的获取
var csrfToken = $('meta[name="csrf-token"]').attr('content');
var csrfField = "";
if (csrfToken) {
var csrfParam = $('meta[name="csrf-param"]').attr('content');
csrfField = "<input type='hidden' name='" + csrfParam + "' value='" + csrfToken + "' />";
}

然后在下面的dialogContent里加入csrfField的内容,使之 变成:

var dialogContent = ( (settings.imageUpload) ? "<form action=\"" + action +"\" target=\"" + iframeName + "\" method=\"post\" enctype=\"multipart/form-data\" class=\"" + classPrefix + "form\">" : "<div class=\"" + classPrefix + "form\">" ) +
( (settings.imageUpload) ? "<iframe name=\"" + iframeName + "\" id=\"" + iframeName + "\" guid=\"" + guid + "\"></iframe>" : "" ) +
"<label>" + imageLang.url + "</label>" +
"<input type=\"text\" data-url />" + (function(){
return (settings.imageUpload) ? "<div class=\"" + classPrefix + "file-input\">" +
"<input type=\"file\" name=\"" + classPrefix + "image-file\" accept=\"image/*\" />" +
csrfField +
"<input type=\"submit\" value=\"" + imageLang.uploadButton + "\" />" +
"</div>" : "";
})() +
"<br/>" +
"<label>" + imageLang.alt + "</label>" +
"<input type=\"text\" value=\"" + selection + "\" data-alt />" +
"<br/>" +
"<label>" + imageLang.link + "</label>" +
"<input type=\"text\" value=\"http://\" data-link />" +
"<br/>" + csrfField +
( (settings.imageUpload) ? "</form>" : "</div>");

注意红字所在地方,其实就加了这个字段而已。再次提交图片上传的时候,不会再报400错误了。

wordpress 升级遇到问题

wordpress 升级遇到问题

升级wordpress的时候遇到:Briefly unavailable for scheduled maintenance. Check back in a minute.

其实解决方法很简单,到wordpress的根目录下。删除 .maintenance 文件即可。
ThinkPHP group count

ThinkPHP group count

如果用sql语句来写group by 再count,这样的sql太容易 了。但由于现在都是在用框架,反而这类sql变得难写了。最近在折腾一个用TP 3框架写的代码,原来代码里写的是:

$count = D('Album')->table(T('albums AS a'))
->join(T('union AS u') . ' ON u.id=a.union_id')
->join(T('company AS c') . ' ON c.id=a.store_id')
->join(T('photo AS p') . ' ON a.id=p.parent_id')
->field('a.*,u.name AS union_name,c.name as store_name')
// ->field('count(a.id)')
->where($where)
->group('a.id')
->count();

看起来好象没有问题,但事实上。出来的结果却并不是你想要的,这个count并不是你要的count,而是每个组的条数。当然你也可以用select()来查出数据,再count($count)一下,但如果数据量过大。这样会崩溃 的。

最终用这样的方法解决了:

$numsQuery = D('Album')->table(T('albums AS a'))
->join(T('union AS u') . ' ON u.id=a.union_id')
->join(T('company AS c') . ' ON c.id=a.store_id')
->join(T('photo AS p') . ' ON a.id=p.parent_id')
->field('a.*,u.name AS union_name,c.name as store_name')
// ->field('count(a.id)')
->where($where)
->group('a.id')
->buildSql();
$nums = D()->table("{$numsQuery} as t")->count();

算是曲线求国吧。

其实很多人在问这种问题了,但更多的人建议是直接写sql。我这种是不写sql的啦 ~

composer引用本地git做为源库

composer引用本地git做为源库

PHP使用者大多对composer是又爱又恨,爱的是composer require后,很多类库不用去下载了,恨的是网速卡成翔,虽然国内有很多道友做了镜象,但对于bower库这些都还是整体更新。

那么,如何只利用composer的基本功能来为自己服务呢?composer的官网有介绍,只要在composer.json中加入几行代码就行了。。

"repositories":[
{
"type":"git",
"url":"/var/www/gouki/test/"
},
]

上面的代码中/var/www/gouki/test,是我的一个git库。也是按照composer的标准来建的。里面只有一个composer.json文件:

{
"name":"gouki/test",
"description":"test",
"authors":[
{
"name":"gouki",
"email":"xxxx@qq.com"
}
],
"minimum-stability":"dev",
"require":{},
"autoload":{
"psr-4":{
"gouki\\test\\":"src/"
}
},
"extra":{
"branch-alias":{
"dev-master":"1.0.x-dev"
}
}
}

src目录下的代码中使用的namespace就是gouki\test,然后在原项目的composer.json中再加入:

"require":{
"gouki/test":"dev-master"
},

最后,运行一下composer update,你会看到项目的根目录下多了vendor目录,同时,vendor目录下也会多一个gouki/test的目录,至此项目引入成功,如果还不放心,那就看一下:vendor/composer/autoload_psr4.php中有没有gouki/test。

之所以这么做,就是因为前文所说的速度,当然也有小团队的成本。比如写个类,就可以直接composer进行加载了。

问题就这么来了,如果放到线上去,那上面的

"repositories":[
{
"type":"git",
"url":"/var/www/gouki/test/"
},
]
需要改为:
"repositories":[
{
"type":"git",
"url":"http://xxxx.xxx.xxx/git"
},
]

如果该git是public的,则不需要任何处理,如果git是需要登录的,则需要在项目的根目录下(和composer.json平级的目录)增加一个auth.json,里面也就两三行代码

{
"http-basic":{
"http://xxxx.xxx.xxx/git":{
"username":"",
"password":""
}
}
}

当然如果你是ssh免登陆的git则另计。至此一个小小的自建composer源就已经完成。

Composer的Illegal offset type in isset or empty

Composer的Illegal offset type in isset or empty

标题的内容也是手贱导致的,本来composer不self-update也不会出现这个问题,这不,一升到最新的composer就出问题了

1、由于我们为了追求速度,大部分都是用的国内的源,这些源往往都不是https的,这回好了,出错了。
Your configuration does not allow connection to http://packagist.phpcomposer.com. See https://getcomposer.org/doc/06-config.md#secure-http for details.
http://packagist.phpcomposer.com could not be fully loaded, package information was loaded from the local cache and may be out of date
OK,打开https://getcomposer.org/doc/06-config.md#secure-http查看了一下,在composer.json和~/.composer/config.json中的config节点下,增加:"secure-http":false
2、composer update的时候报:
Installation failed, reverting ./composer.json to its original content.
OK,现在可以用composer diag来检查 一下了,结果 发现:
composer diag
Checking composer.json: FAIL
No license specified, it is recommended to do so. For closed-source software you may use "proprietary" as license.
require.yiisoft/yii2 : unbound version constraints (*) should be avoided
Checking platform settings: OK
Checking git settings: OK
Checking http connectivity to packagist: OK
Checking https connectivity to packagist: OK
Checking github.com oauth access: OK
Checking disk free space: OK
Checking pubkeys:
Tags Public Key Fingerprint: ???? 已隐藏
Dev Public Key Fingerprint: ????? 已隐藏
OK
Checking composer version: FAIL
You are not running the latest stable version, run `composer self-update` to update (e8b1a5f35772e39ca21ab855a278bd84a0a534b2 => 1.0.0-beta2)
居然显示 ,composer中一定要有license节点,require的也需要带 版本号了。于是一一加上,然后接着composer update
3、出现如标题一般的错误
处理方法:一般出现这种错误 ,大部分情况下是fxp插件需要更新了,执行composer global require fxp/composer-asset-plugin --prefer-dist,
Changed current directory to /Users/gouki/.composer
Using version ^1.1 for fxp/composer-asset-plugin
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
- Removing fxp/composer-asset-plugin (v1.1.1)
- Installing fxp/composer-asset-plugin (v1.1.2)
Downloading: 100%

Writing lock file
Generating autoload files
更新完后,再composer udpate就OK了!
当然如果还有问题,你应该查看官网的issue,比如:https://github.com/francoispluchino/composer-asset-plugin/issues/191,刚开始的时候确实是BUG,后面更新了就好了。哈哈

uploadify-v2.1.4-www.7es.cn.rar

The file or directory to be published does not exist: vendor/bower/jquery/dist

标题所说的问题可能早期用户都遇到过。但其实这个问题在官方也早就有解决方案了,不知道为什么还有人问起。

这其实是与:fxp/composer-asset-plugin 相关的一个BUG,你在global require的时候,用1.1的beta版就没问题了。
很简单就能发现这个问题了,你先:composer global require "fxp/composer-asset-plugin:~1.1.1",然后composer install就OK了。
其实你如果每次composer update报这个错,你就应该有警惕了:
Deprecation Notice: The Composer\Package\LinkConstraint\MultiConstraint class is deprecated, use Composer\Semver\Constraint\MultiConstraint instead. in phar:///usr/local/bin/compose
r/src/Composer/Package/LinkConstraint/MultiConstraint.php:17
Deprecation Notice: The Composer\Package\LinkConstraint\LinkConstraintInterface interface is deprecated, use Composer\Semver\Constraint\ConstraintInterface instead. in phar:///usr/l
ocal/bin/composer/src/Composer/Package/LinkConstraint/LinkConstraintInterface.php:17
当然如果你操作完后还是没看到有任何反应,OK,先清除cache......
不多说,Over

7295467ef304c55f6c7cb724fbea4bda