标签归档:Yii2

Yii2按需加载js,css文件,并自动加上时间戳

网上找遍了国内和国外的资料,没有能够为动态增加的文件加上时间戳的,进过分析Yii2源码,发现其实非常简单:

开启assetManager支持自动加上时间戳

修改main.php

    'assetManager' => [
        'appendTimestamp' => true,
    ],

视图层按需加载js,css

$bundle=AppAsset::register($this);
$bundle->js[]='js/windowview.js';
$bundle->css[]='css/robot.css';

yii gridview 使用target=”_blank”无效

解决办法是设置format为raw:

        [
            'attribute' => 'attribute',
            'format' => 'raw',
            'value' => function ($model, $key, $index, $column) {
                return  Html::a($model->title, ['view', 'id' => $model->id], ['target' => '_blank']);
            },
        ],

Yii2设置变量到布局layout

通过全局params配置

Yii::$app->params['myVar']

通过session

Yii::app()->session['myvar']

或者通过Flash Message

通过控制器传递变量方式

首先,需要再控制器添加参数

class SiteController extends CController {

    public $myvar;
//...

然后在layout/main.php获取控制器变量

$this->context->myvar
Yii::$app->controller->myvar

Yii2 文件上传扩展

官方指南

aminkt/yii2-upload-manager

Upload manager system based and inspired from WordPress upload manager.

yii2-image-manager

A module/widget for upload, manage and cropping images

yii2-attachments

Extension for file uploading and attaching to the models

yii2-widget-fileinput

An enhanced FileInput widget for Bootstrap 3.x with file preview, multiple selection, and more features

yii2-file-input-widget

Jasny File Input Bootstrap Widget + Local and Remote storage

yii2-file-upload

PHP library for uploading files to your server or Amazon S3

yii2-upload-file

Yii2 tools for upload file

给Yii composer提速

Yii 2 的 2.1x版本后,采用asset-packagist.org给bower提速,效果明显,旧版本Yii要升级到新版本可以采用以下步骤:

修改 composer.json

  "config": {
    "process-timeout": 1800,
    "fxp-asset": {
      "enabled": false
    }
  },
  "repositories": [
    {
      "type": "composer",
      "url": "https://asset-packagist.org"
    }
  ]

修改config/main.php

'aliases' => [
    '@bower' => '@vendor/bower-asset',
    '@npm'   => '@vendor/npm-asset',
],

清理composer并运行

composer clear-cache
composer install

解决nginx+php/java/go/python+mysql下time_wait连接数过多问题

公司服务器连接数超过10K了,查了下大多数是没有即时回收,采用tcp复用容易后程序出现了故障,以前一直看到说PHP持久连接有问题,所以没怎么用,最近有机会试了下。

非常香,连接数直接降低到几百了,目前观察数周没有问题。

查看连接数

netstat -n |  wc -l # 总连接数
netstat -n | grep -i time_wait | wc -l # time_wait 连接数
netstat -anp # 查看占用端口过多的程序

tcp复用解决方案

网上大部分解决方案是修改sysctl.conf回收重用ipv4连接,但是可能带来其他问题

net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_timestamps=1
net.ipv4.tcp_tw_reuse=1
net.ipv4.tcp_tw_recycle=1
net.ipv4.tcp_fin_timeout=30
net.ipv4.tcp_keepalive_time = 600

nginx fastcgi(php) 解决方案

修改nginx.conf

upstream fastcgi_backend {
    server 127.0.0.1:9000;
    keepalive 60;
}

location ~ \.php$ {
        fastcgi_pass  fastcgi_backend;
        fastcgi_keep_conn on;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
}

主要是 fastcgi_keep_conn onupstreamkeepalive

nginx + proxy (python/go/java) 解决方案

upstream wxpic {
    keepalive 60;
    server 127.0.0.1:xxx;
}

server {
    keepalive_requests 10000; # 默认100
    location / {
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}

主要是 proxy_http_version, proxy_set_header Connection ""以及keepalive_requests

mysql数据库连接解决方案

修改yii数据库配置采用长链接

'db' => [ 
    'class' => 'yii\db\Connection',
    'dsn' => '*', 'username' => '*', 
    'password' => '*', 
    'charset' => 'utf8mb4', 
    'attributes' => [ 
       PDO::ATTR_PERSISTENT => true 
    ]
],

redis 连接数

php redis连接数过多解决办法(Yii,predis,phpredis等)

Yii2 composer安装慢的解决办法

修改fxp-asset为Asset Packagist

参考官方安装指南Yii advanced template installation提到:

It uses asset-packagist for managing bower and npm package dependencies through Composer. Also you can use asset-plugin, as in earlier versions, but it works slowly.

找到

"config": {
    "process-timeout": 1800,
    "fxp-asset":{
        "installer-paths": {
            "npm-asset-library": "vendor/npm",
            "bower-asset-library": "vendor/bower"
        }
    }
},
"replace": {
    "bower-asset/jquery": ">=1.11.0",
    "bower-asset/inputmask": ">=3.2.0",
    "bower-asset/punycode": ">=1.3.0",
    "bower-asset/yii2-pjax": ">=2.0.0"
}

修改为

"config": {
    "process-timeout": 1800,
    "fxp-asset": {
        "enabled": false
    }
},
"repositories": [
    {
        "type": "composer",
        "url": "https://asset-packagist.org"
    }
]

修改config/main.php

'aliases' => [
    '@bower' => '@vendor/bower-asset',
    '@npm'   => '@vendor/npm-asset',
],

Asset Packagist介绍

from https://asset-packagist.org/

Composer + Bower + NPM = friends forever!

This repository allows installation of Bower and NPM packages as native Composer packages.

NO plugins and NO Node.js are required.

At the moment we’ve added most popular Bower and NPM packages 4000+ each.

In case Composer fails to install some asset package, use the search line at the top of the page to check specific package health.

For NPM scoped packages use scope--package instead of @scope/package, e.g. npm-asset/pusher--chatkit.

Got tired of fxp/composer-asset-plugin.

Why Asset Packagist

Got tired of fxp/composer-asset-plugin.

It’s a good project with nice idea and good implementation. But it has some issues: it slows down composer update a lot and requires global installation, so affects all projects. Also there are Travis and Scrutinizer integration special problems, that are a bit annoying.

yii2 实现tree grid

yii2-gtreetable

Extension of Yii 2 Framework, which is wrapper for bootstrap-gtreetable plugin, on the other hand it provides functionality which allows to save the nodes states into database. http://gtreetable2.gilek.net

yii2-nested-sets

The nested sets behavior for the Yii framework.

yii2-treegrid

jQuery TreeGrid Extension for Yii 2

This is the jQuery TreeGrid extension for Yii 2. It encapsulates TreeGrid component in terms of Yii widgets, and thus makes using TreeGrid component in Yii applications extremely easy.

tree-manager

An enhanced tree management module from Krajee with inbuilt jQuery plugins and Yii widgets for tree node manipulation and management using nested sets. The module provides ability to manage hierarchical data stored using nested sets. It utilizes the yii2-nested-sets extension to manage the tree structure in your database. Refer the documentation for yii2-nested-sets extension before you start using this module. The yii2-tree-manager module includes two major widgets TreeView and TreeViewInput. In addition, it includes module level settings to easily configure your tree management preferences. It includes a Tree Model which includes inbuilt tree management flags and rules. The model implements and uses a TreeTrait. So one can choose to extend from the Tree Model or implement their own model that uses the TreeTrait. It also includes a NodeController that allows you to manage tree nodes easily via ajax. The tree view widgets and jQuery plugins are built from scratch by Krajee entirely without using any third party plugins. The TreeView is designed using HTML5, jQuery & CSS3 features to work along with the Yii 2 framework.

View a complete demo for TreeView or TreeViewInput.

使用国内镜像快速安装composer以及yii2(附安装脚本)

通过中国镜像安装composer

参考文章 如何安装 Composer

下载安装文件

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('SHA384', 'composer-setup.php') === '93b54496392c062774670ac18b134c3b3a95e5a5e5c8f1a9f115f203b75bf9a129d5daa8ba6a13e2cc8a1da0806388a8') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

安装

php composer-setup.php

删除安装文件

php -r "unlink('composer-setup.php');"

设置全局路径(windows请按参考文档设置)

sudo mv composer.phar /usr/local/bin/composer

配置使用国内镜像

composer config -g repo.packagist composer https://packagist.phpcomposer.com

安装Yii2

参考文章 Install via Composer

首先安装 Composer Asset Plugin

composer global require "fxp/composer-asset-plugin:^1.2.0"

安装基础模板

php composer.phar create-project yiisoft/yii2-app-basic yiitest

安装高级模板

php composer.phar create-project yiisoft/yii2-app-advanced yiitest

安装过程中如果提示“please create a GitHub OAuth token to go over the API rate limit”,登录github,在https://github.com/settings/tokens生成一个token,权限只需要勾选repo即可

进入项目目录

cd yiitest

测试安装环境

php requirements.php

初始化项目

 ./init

运行项目

./yii serve/index -h
./yii serve/index -t="@frontend/web"
./yii serve/index -t="@backend/web"