咕噜

In Life Like Code


  • 首页

  • 归档

  • 关于

vagrant-up-提示mount-unknown-filesystem-type-vboxsf

发表于 2018-05-20

设置vagrantfile的配置文件时并设置同步目录,vagrant up出现错误,解决方案

方案一:安装[VirtualBox Guest Addittions]增强插件

进入虚拟机中

1
2
3
4
5
6
sudo -i
mkdir -p /apps/vbox && cd /apps
wget https://download.virtualbox.org/virtualbox/5.2.10/VBoxGuestAdditions_5.2.10.iso #请根据virtualbox版本下载相应的版本号
sudo mount -o loop,ro VBoxGuestAdditions_5.2.10.iso vbox/
sudo sh vbox/VBoxLinuxAdditions.run
sudo umount vbox/

登出虚拟机并重新加载

1
vagrant reload

方案二:安装vagrant插件

vagrant的在本地的安装目录下执行如下命令:

1
2
3
sudo vagrant plugin install vagrant-vbguest #安装vagrant插件
vagrant halt #关机
vagrant up #重启

如何利用vagrant搭建kafka集群

发表于 2018-03-25

vagrant环境搭建

安装vagrant与virtualBox基本软件

下载地址vagrant:https://www.vagrantup.com/downloads.html virtualBox:https://www.virtualbox.org/wiki/Downloads。自行下载os系统版本并next安装完毕,验证,终端运行vagrant -v显示出版本号则安装正确

利用vagrant安装unix系统

具体安装教程详见:vagrant入门
创建三个系统目录分别为:

1
$ mkdir -p ~/bigdata/centos-1 ~/bigdata/centos-2 ~/bigdata/centos-3

进到centos-1目录并执行以下命令

1
2
$ vagrant init centos/7
$ vagrant up

运行vagrant up后,则程序会自行下载一个boxes,可将下载url复制出来到迅雷下载并中断程序(如下载慢),如图:
kafka安装程序图片
boxex下载列表详见:https://app.vagrantup.com/boxes/search
如是迅雷下载执行以下命令添加本地boxes

1
2
$ vagrant box add centos-1 ~/data/download/xxx.box
#注解 vagrant box add [box名称] [box本地路径]

进入安装新系统中则运行如下命令:

1
$ vagrant ssh

NOTE:执行以下步骤安装剩下两台虚拟机器centos-2、centos-3即可

unix虚拟机配置

编辑根目录下Vagrantfile文件

1
$ subl Vagrantfile

subl别名配置教程终端命令启动subline text
替换文件全部如下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.box = "centos/7"
#以下不同系统IP请不要一样。每个系统换成192.168.10.12、192.168.10.13这样子
config.vm.network "private_network", ip: "192.168.10.11"
config.vm.provider "virtualbox" do |vb|
vb.memory = "1024"
vb.cpus = 2
end
end

执行以下命令生效配置并逐一centos-2、centos-3目录的Vagrantfile内容

1
$ vagrant provision

安装kafka数据流与zookeeper

预先工作

三台机子同时创建数据目录:

1
2
3
4
$ sudo -i
$ mkdir -p /apps/kafka
$ mkdir -p /apps/zk_data
$ cat [number] > /apps/zk_data/myid #[number]代表数字。每台确保唯一不同

编辑/etc/hosts文件,添加如下内容在集群机

1
2
3
192.168.10.11 centos71
192.168.10.12 centos72
192.168.10.13 centos73

下载kafka、zookeeper

1
2
3
4
$ wget http://mirror.bit.edu.cn/apache/kafka/1.0.0/kafka_2.11-1.0.0.tgz
$ wget http://mirrors.hust.edu.cn/apache/zookeeper/zookeeper-3.4.11/zookeeper-3.4.11.tar.gz
$ tar -zxf kafka_2.11-1.0.0.tgz && mv kafka_2.11-1.0.0 /apps/kafka
$ tar -zxf zookeeper-3.4.11.tgz && mv zookeeper-3.4.11 /apps/zookeeper

配置并启动kfka、zookeeper

进入zookeeper目录,添加如下基本运行配置

1
2
3
4
5
6
7
8
9
10
11
12
$ cp conf/zoo_sample.cfg conf/zoo.cfg
$ cat > conf/zoo.cfg << EOF
> dataDir=/apps/zk_data #zk的数据目录并会读取该目录下myid
> clientPort=2181
> tickTime=2000
> initLimit=5
> syncLimit=2
> server.1=centos71:5168:5166
> server.2=centos72:5168:5166
> server.3=centos73:5168:5166
> EOF
$ zookeeper/bin/zkServer.sh start

进入kafka目录,添加如下基本运行配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$ cat > config/server.properties << EOF
> broker.id=1
> listeners=PLAINTEXT://centos71:9092
> num.network.threads=3
> num.io.threads=8
> socket.send.buffer.bytes=102400
> socket.receive.buffer.bytes=102400
> socket.request.max.bytes=104857600
> log.dirs=/data/kafka-logs
> num.partitions=3
> offsets.topic.replication.factor=1
> transaction.state.log.replication.factor=1
> transaction.state.log.min.isr=1
> log.retention.hours=168
> log.segment.bytes=1073741824
> log.retention.check.interval.ms=300000
> zookeeper.connect=centos71:2181,centos72:2181,centos73:2181
> zookeeper.connection.timeout.ms=1000000
> group.initial.rebalance.delay.ms=0
> EOF
$ bin/kafka-server-start.sh -daemon config/server.properties

依次对集群对以上进行相同步骤就可。具体配置详细请参考官网文档(本人菜鸟一粒)

执行如下命令进行验证成功与否

1
$ bin/kafka-topics.sh --create --zookeeper centos71:2181 --replication-factor 1 --partitions 1 --topic test66

出现Created topic “test66”.字眼恭喜成功了。

总结

还是很菜,学习还要继续!下一章将进行如何操作利用php、py、java进行操作kafka!

php-process-deamons[转载]

发表于 2018-02-08
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
class JobDaemon{
public $maxProcesses = 3;
protected $jobsStarted = 0;
protected $currentJobs = array();
protected $signalQueue=array();
protected $parentPID;
protected $redis;
public $log = '/daemons.log';
public function __construct(){
echo "constructed \n";
$this->parentPID = getmypid();
pcntl_signal(SIGCHLD, array($this, "childSignalHandler"));
}
/**
* Run the Daemon
*/
public function run(){
echo "Running \n";
for($i=0; $i<10000; $i++){
$jobID = rand(0,10000000000000);
while(count($this->currentJobs) >= $this->maxProcesses){
echo "Maximum children allowed, waiting...\n";
sleep(1);
}
$launched = $this->launchJob($jobID);
}
//Wait for child processes to finish before exiting here
while(count($this->currentJobs)){
echo "Waiting for current jobs to finish... \n";
sleep(1);
}
}
/**
* Launch a job from the job queue
*/
protected function launchJob($jobID){
$pid = pcntl_fork();
if($pid == -1){
//Problem launching the job
error_log('Could not launch new job, exiting');
return false;
}
else if ($pid){
// Parent process
// Sometimes you can receive a signal to the childSignalHandler function before this code executes if
// the child script executes quickly enough!
file_put_contents($this->log, "{$pid}-running\n", FILE_APPEND);
$this->currentJobs[$pid] = $jobID;
// In the event that a signal for this pid was caught before we get here, it will be in our signalQueue array
// So let's go ahead and process it now as if we'd just received the signal
if(isset($this->signalQueue[$pid])){
echo "found $pid in the signal queue, processing it now \n";
$this->childSignalHandler(SIGCHLD, $pid, $this->signalQueue[$pid]);
unset($this->signalQueue[$pid]);
}
}
else{
//Forked child, do your deeds....
/**
* @var $redis Redis
*/
$redis = new Redis();
$redis->pconnect('127.0.0.1', 6379, 2.5);
while (true) {
$data = $redis->rPop('test_key');
if ($data !== false){
file_put_contents($this->log, "{$data}\n", FILE_APPEND);
}else{
file_put_contents($this->log, "数据为空\n", FILE_APPEND);
}
}
$exitStatus = 0; //Error code if you need to or whatever
echo "Doing something fun in pid ".getmypid()."\n";
exit($exitStatus);
}
return true;
}
public function childSignalHandler($signo, $pid=null, $status=null){
//If no pid is provided, that means we're getting the signal from the system. Let's figure out
//which child process ended
if(!$pid){
$pid = pcntl_waitpid(-1, $status, WNOHANG);
}
//Make sure we get all of the exited children
while($pid > 0){
if($pid && isset($this->currentJobs[$pid])){
$exitCode = pcntl_wexitstatus($status);
if($exitCode != 0){
echo "$pid exited with status ".$exitCode."\n";
}
unset($this->currentJobs[$pid]);
}
else if($pid){
//Oh no, our job has finished before this parent process could even note that it had been launched!
//Let's make note of it and handle it when the parent process is ready for it
echo "..... Adding $pid to the signal queue ..... \n";
$this->signalQueue[$pid] = $status;
}
$pid = pcntl_waitpid(-1, $status, WNOHANG);
}
return true;
}
}
$obj = new JobDaemon();
$obj->run();

centos7.3 编译安装php7.1.8

发表于 2017-08-12

##下载并解压文件

1
$ cd /tmp &$
1
./configure --prefix=/opt/php7.1 --sysconfdir=/etc --localstatedir=/var --datadir=/usr/share/php --mandir=/usr/share/man --with-zlib-dir --with-freetype-dir --enable-mbstring --with-libxml-dir=/usr --enable-soap --enable-calendar --with-curl --with-mcrypt --with-zlib --with-gd --disable-rpath --enable-inline-optimization --with-bz2 --with-zlib --enable-sockets --enable-sysvsem --enable-sysvshm --enable-pcntl --enable-mbregex --enable-exif --enable-bcmath --with-mhash --enable-zip --with-pcre-regex --with-pdo-mysql --with-jpeg-dir=/usr --with-png-dir=/usr --enable-gd-native-ttf --with-openssl --with-fpm-user=nginx --with-fpm-group=nginx --with-imap --with-imap-ssl --with-kerberos --with-gettext --with-xmlrpc --with-xsl --enable-opcache --enable-fpm

整套web环境搭建

发表于 2017-05-22

install php5.3

  • 安装运行依赖包&下载php5.3 tar包
1
2
3
4
5
$ yum -y install epel-release && yum -y groupinstall 'Development Tools'
$ yum -y install libxml2-devel libcurl-devel libjpeg-devel libpng-devel freetype-devel libmcrypt-devel openssl-devel libtool-ltdl-devel
$ cd ~/tmp
$ wget http://cn2.php.net/distributions/php-5.3.29.tar.gz
$ tar zxvf php-5.3.29.tar.gz && cd php-5.3.29
  • 配置资源
1
$ ./configure --prefix=/opt/php-5.3.29 --with-config-file-path=/opt/php-5.3.29/etc --enable-fpm --with-mysql=mysqlnd --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-iconv-dir --with-zlib --with-libxml-dir --enable-xml --with-curl --with-openssl --with-mhash --with-xmlrpc --with-gettext --with-freetype-dir --with-jpeg-dir --with-png-dir --with-gd --enable-gd-native-ttf --with-mcrypt --enable-bcmath --enable-shmop --enable-exif --enable-sysvsem --enable-mbregex --enable-mbstring --enable-sockets --enable-ftp --enable-zip --enable-soap
  • 编译&安装
1
make && make install
  • 设置相关配置
1
2
3
4
5
6
$ cp php.ini-production /opt/php-5.3.29/etc/php.ini
$ cp /opt/php-5.3.29/etc/php-fpm.conf.default /opt/php-5.3.29/etc/php-fpm.conf
$ cp sapi/fpm/init.d.php-fpm /etc/init.d/php53-fpm
$ chmod 755 /etc/init.d/php53-fpm
$ chkconfig php53-fpm on
$ /etc/init.d/php53-fpm start

安装nginx

  • 安装nginx1.12.0版本所以要配置最新的yum源;接下来就是安装运行了。
1
2
3
4
5
6
7
$ vi /etc/yum.repos.d/nginx.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1
$ yum -y install nginx

安装Percona Server 5.7

  • 安装percona仓库源
1
yum install http://www.percona.com/downloads/percona-release/redhat/0.1-4/percona-release-0.1-4.noarch.rpm
  • 检验安装是否成功||直接安装服务
1
2
3
$ yum list | grep percona
$ yum install -y Percona-Server-server-57
$ service mysql start
  • NOTE要点
  1. 临时密码存放在/var/log/mysqld.log,执行以下便得到
1
cat /var/log/mysqld.log | grep "temporary password"
  1. 必须更改root临时密码,执行以下&&按照提示操作更改密码
1
sudo /usr/bin/mysql_secure_installation

服务器关闭密码登录&&配置ssh

创建用户并设置。分配拥有sudo用户组

1
2
3
4
5
6
7
8
$ useradd example_user && passwd example_user
$ usermod -aG wheel example_user
#创建授权目录
$ mkdir ~/.ssh
$ echo>~/.ssh/authorized_keys
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/*

执行&配置ssh相关操作

  • 在本机生成密钥执行以下命令
1
ssh-keygen -b 4096

出现如图
回车将要求你填入一个key密码;按提示执行之后将生成私钥test、公钥test.pub文件

  • 将生成好test.pub传到服务器
1
scp ~/.ssh/test.pub ssh user@ip:~/.ssh/authorized_keys
  • 登录到服务器编辑sshd_config文件
1
2
3
4
5
6
7
8
9
#更改/etc/ssh/sshd_config内容
$ vi /etc/ssh/sshd_config #编辑以下内容
Port 1688 #把端口设为1688
RSAAuthentication yes #把#去掉
PubkeyAuthentication yes 把#去掉
PasswordAuthentication no #设置为no
PermitRootLogin no #如果不想让root登录改为no,note无密钥测试登录成功再修改此项。
$ service sshd restart #重启sshd服务

进行ssh无密钥连接服务器

本机用Sublime打开 sbul ~/.ssh/config 尾部添加以下内容:

1
2
3
4
5
6
Host sexy #别名
HostName ip #ip地址
Port 1688 #端口;上边更改过来的端口
User sexbody #登录用户名
PreferredAuthentications publickey
IdentityFile ~/.ssh/test #上边创建的test私钥文件

iTerm终端执行ssh sexy #上边config文件添加的别名;将出现以下信息。输入刚才创建ssh-keygen时的密码。连接成功
出现如图

使用gitolite创建git服务仓库

  • 根据上边操作生成名为git的ssh-key,然后上传到服务器/tmp目录备用
1
scp git.pub ssh sexy:/tmp
  • 创建只具有读写的系统账号
1
2
3
$ useradd --system --shel /bin/bash --create-home git
$ usermod -u 600 git
$ cp /tmp/git.pub /home/git/ #把公钥复制git用户目录备用
  • 切换到刚创建git用户&&创建bin目录
1
2
3
$ su - git
$ pwd #或者echo $HOME; 校验是不是已经切到git用户目录
$ mkdir -p ~/bin
  • 克隆gitolite源码&&安装
1
2
3
git clone git://github.com/sitaramc/gitolite
gitolite/install -ln ~/bin
gitolite setup -pk git.pub #刚才复制到此目录的公钥
  • 本地配置.ssh/config并进行别名连接配置
1
git clone git:gitolite-admin #克隆权限管理与仓库管理回来

至此整个服务已经搭建好。

MAC创建subline text 终端命令与subline text build 运行php7或者python3环境

发表于 2017-04-07

subline text command 运行并配置php7与python3运行环境

终端命令启动subline text

  1. 打开终端或者iTerm 运行以下代码
1
2
3
4
5
➜ ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl #创建软连接 -> /usr/local/bin/任意名称
➜ vi ~/.bash_profile #输入以下内容结尾
➜ export PATH=$PATH:~/usr/local/bin
➜ source ~/.bash_profile #生效配置
➜ subl filename #能启动sublime 则配置成功,good job.

配置php7 、python3 build环境在 subline text

php7

  1. 在sublime text 菜单栏中点击Tools->Build System->New Build System
  2. 复制以下内容覆盖到上边新打开的文件中

    1
    2
    3
    4
    5
    {
    "cmd": ["/usr/local/opt/php71/bin/php", "$file"], # 可使用which php 查看PHP7具体命令在哪里
    "file_regex": "php$",
    "selector": "source.php"
    }
  3. 然后直接弹出目录中保存并命名为php.sublime-build

  4. 打开Tools->Build System->New 出现如图
    5.打开一个php文件,然后按command键+B运行PHP代码

    python3

  5. 配置内容如下,并重复以上步骤即可
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    {
    "auto_complete_triggers":
    [
    {
    "characters": ".",
    "selector": "source.python - string - constant.numeric"
    }
    ],
    "extensions":
    [
    "py"
    ]
    }

具体内容请参考 sublime text官方文档

真机安装centos7与scrapy爬虫环境

发表于 2016-08-17

真机安装centos7与scrapy爬虫环境

1
2
网上大部分教程都是用ultraiso来录镜像的。但我在制作过程中一直遇到`设备忙;请格式化xxx`信息
谷歌找到usbwriter<https://sourceforge.net/projects/usbwriter/>此工具。结果制作成功

安装python35(用yum安装)

  1. 执行

    1
    $ sudo yum install centos-release-scl
  2. 再执行

    1
    2
    sudo yum install rh-python35
    $ scl enable rh-python35 bash
  3. 如果我们想开机启动就使软件集合可以编辑

    1
    2
    3
    4
    5
    vi /etc/profile.d/python35.sh
    #写入以下内容
    js #!/bin/bash
    source /opt/rh/rh-python35/enable
    export X_SCLS="`scl enable rh-python35 'echo $X_SCLS'`"

安装scrapy

  1. 执行命令
    pip install Scrapy
    此过程中;不断报错告诉你缺少哪个依赖库。
    
  2. 根据缺少的依赖库用yum命令来安装相应的库

安装java

  1. 下载rpm
    sudo wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u66-b17/jdk-8u66-linux-x64.rpm" 
    #或者直接到官网下载最新rpm再上传到服务器(有墙)
    
  2. 如出现无wget;运行yum install wget来安装wget。
  3. 运行
    sudo rpm -ivh jdk-8u66-linux-x64.rpm 
    jdk-8u66-linux-x64.rpm 是你下载回来的rpm名称
    
  4. java -version 查看版本信息 NOTE:跑jar包出错可能是缺少ia32-libs库或者执行yum install xulrunner.i686

生成安全的PHP随机数和密码 | generate security strong PHP random

发表于 2016-03-07

生成安全的PHP随机数和密码(php5.3+)

随机数

一般我们都是使用rand,mt_rand由这些函数来组是不太安全的。

  1. linux附带两个接口的随机数,/dev/random(专家说有阻塞性web哪就不适合用) /dev/urandom合适生成安全的php随机数。使用fopen fread来读取内容。
    1.详见
  2. mcrypt_create_iv() 和 openssl_random_pseudo_bytes()来生成随机数,再用bin2hex把ASCII码转成16进制

密码

1.到现我们可能还在使用md5算法加密方式,在官方文档http://php.net/manual/zh/function.md5.php都明确注释(NOTE)依赖md5算法来对明文加密不够复杂且也不推荐,哪今天介绍几种加密算法

官方说的”盐”,password_hash()或者crypt()来保存”盐”,password_verify()或者crypt()对密码进行验证。官方说明图如下:

1
2
3
4
5
6
7
8
9
10
$pwd = "test123";//原密码
$algorithm = '$2y$'; //基于BlowFish
$algorithmOptionsCost = '10$';
$salt = bin2hex(openssl_random_pseudo_bytes(32));//也可以用上面提到的bin2hex(mcrypt_create_iv())和bin2hex(fread(fopen('/dev/urandom')),32)
$encryption = crypt($pwd, $algorithm . $algorithmOptionsCost . $salt . '$');
if ($encryption === crypt($pwd, substr($encryption,0, 29)))
echo 'yes';
else
echo 'no';
}
1
2
3
4
5
6
7
8
//password_hash()是crypt()的简单封装版
$pwd = "test123";//原密码
$option = ['salt'=>bin2hex(mcrypt_create_iv(32))];
$encryption = password_hash($pwd, PASSWORD_BCRYPT, $option) //加密的密码
if(password_verify($pwd, $encryption))
echo 'yes';
else
echo 'no'

对称加密方式(symmetric encryption) phpversion5.5+

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
function AESEncrypt($text, $key) {
$ivsize = openssl_cipher_iv_length('aes-256-cbc'); //生成iv的长度
$iv = openssl_random_pseudo_bytes($ivsize); //生成字符串
$keys = hash_pbkdf2('sha256', $key, $iv, 80000, 64, true); //生成keys
$encKey = substr($keys, 0, 32); // 分隔encryption的key
$hmacKey = substr($keys, 32); // 分隔hmac的key
$ciphertext = openssl_encrypt(
$text,
'aes-256-cbc',
$encKey,
OPENSSL_RAW_DATA,
$iv
);
$hmac = hash_hmac('sha256', $iv . $ciphertext, $hmacKey);
return $hmac . $iv . $ciphertext;
}
}
function AESDecrypt($text, $key) {
$hmac = substr($text, 0, 64);
$ivsize = openssl_cipher_iv_length('aes-256-cbc');
$iv = substr($text, 64, $ivsize);
$ciphertext = substr($text, $ivsize + 64);
// Generate the encryption and hmac keys
$keys = hash_pbkdf2('sha256', $key, $iv, 80000, 64, true);//生成encryption 和 hmac 的key
$encKey = substr($keys, 0, 32);
$hmacNew = hash_hmac('sha256', $iv . $ciphertext, substr($keys, 32));
if (!hash_equals($hmac, $hmacNew)) {
return false;
}
return openssl_decrypt(
$ciphertext,
'aes-256-cbc',
$encKey,
OPENSSL_RAW_DATA,
$iv
);
}

mac brew install php-redis error

发表于 2015-12-30

安装php-redis遇到的问题以及解决方法.

(一)遇到问题

今天在安装php-redis遇到的问题以及解决方法.
执行brew install php55-redis后报错如下

1
2
3
Already downloaded: /Library/Caches/Homebrew/php55-redis-2.2.7.tar.gz
==> /usr/local/opt/php55/bin/phpize
Error: No such file or directory - /usr/local/opt/igbinary/include/igbinary.h

(二)查找问题

遇到问题肯定是到github同性社区找homebrew项目issues寻求答案;
https://github.com/Homebrew/homebrew-php/issues/1910里找到了答案.

(三)解决问题

  1. 执行以下命令
    1
    2
    brew remove php55-redis php55-igbinary
    brew install php55-redis --build-from-source

(四)完成任务

安装完成后,在command打开php.ini

1
2
3
4
5
sudo vi /etc/php.ini
#按键盘上的『N』跑到文本尾部添加
extension=extension=/usr/local/Cellar/php55-redis/2.2.7_1/redis.so
#或者执行检测插件是否安装成功
php -m | grep redis

重起webServer页面运行phpinfo.php有无这扩展最后搞淀.

Yii2的日期插件(Daterangepicker)实用版

发表于 2015-12-08

Yii2的日期插件封装

(一)定义安装目录

1
"directory" : "../yiisoft/vendor/bower"

(二)安装相关插件与注册yii2assets

  1. 打开终端开始安装daterangepicker插件
  2. 运行bower install bootstrap-daterangepicker
  3. 成功后在项目的assets目录新建DaterangepickerAsset的文件.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
namespace app\assets;
use yii\web\AssetBundle;
class DaterangepickerAsset extends AssetBundle
{
public $sourcePath = '@bower';
public $js = [
'moment/moment.js',
'bootstrap-daterangepicker/daterangepicker.js',
];
public $css = [
'bootstrap-daterangepicker/daterangepicker.css'
];
public $depends = [
'yii\bootstrap\BootstrapAsset',
];
}

(三)新建一个日期组件扩展InputWidget类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
namespace backend\componment;
use backend\assets\DaterangepickerAsset;
use yii\widgets\InputWidget;
use yii\helpers\Html;
use yii\helpers\Json;
class Daterangepickper extends InputWidget
{
/**
* @var array
*
*/
public $inputOptions = ['class' => 'form-control'];
public $initConfig = [
'locale'=>[ 'format' => 'YYYY-MM-DD'],
'singleDatePicker'=> true,
'showDropdowns'=> true
];
public $options = [];
public $language;
public $config = [];
public $is_show_applyLabel = true;
public $is_show_cancelLabel = true;
public function init()
{
parent::init(); // TODO: Change the autogenerated stub
if(!isset($this->options['id'])){
$this->options['id'] = $this->getId();
}
}
/**
* Executes the widget.
* @return string the result of widget execution to be outputted.
*/
public function run()
{
parent::run(); // TODO: Change the autogenerated stub
$start = Html::activeTextInput($this->model, $this->attribute.'[start]', ['id'=>$this->options['id'].'start' ,'class' => 'form-control' ]);
$end = Html::activeTextInput($this->model, $this->attribute.'[end]', ['id'=>$this->options['id'].'end' ,'class' => 'form-control' ]);
$html =<<<HTML
<div class="input-group input-daterange">
<div class="">
{$start}
</div>
<span class="input-group-addon">到</span>
<div class="">
{$end}
</div>
</div>
HTML;
echo $html;
$this->registerClientScript();
}
public function registerClientScript(){
$id = $this->options['id'];
$config= Json::encode(array_merge($this->config, $this->initConfig));
$js = "
$('#{$id}start').daterangepicker({$config});
$('#{$id}end').daterangepicker({$config});
";
$view = $this->getView();
DaterangepickerAsset::register($view);
$view->registerJs($js);
}
}

(四)是调用写好的组件

1
2
3
4
5
<div class="row">
<div class="col-md-5">
<?= $form->field($model, 'attribute')->widget(Daterangepicker::className(),$config)?>
</div>
</div>
12
咕噜

咕噜

php教程,yii教程,python教程

11 日志
7 标签
© 2018 咕噜
由 Hexo 强力驱动
主题 - NexT.Muse