为什么localhost无法连接到Mysql数据库?

在做开发的时候肯定无数人都碰到过这种无法连接数据库的情况, 当你把连接的Host改成127.0.0.1以后又正常了.

先来说说两者的区别:
1. 127.0.0.1 127.0.0.1走的是TCP/IP协议。
2. localhost 使用Localhost走的是socket协议.

那就很简单. 证明问题出在Socket身上.

PHP mysql socket配置
我们可以先打印phpinfo()看看php配置里mysqli.default_socket配置

发现指向了/var/mysql/mysql.sock

Mysql Socket配置
接着再看看mysql的socket地址

发现指向了/tmp/mysql.sock

问题很明显了,是这两个Socket不对应

有三种办法解决问题:
1. 修改php.ini把配置指向 /tmp/mysql.sock(具体还是根据mysql配置来)
2. 连接数据库的时候配置Socket

Mysqli
在使用mysqi函数的时候可以看到最后一个是Socket

new mysqli('localhost', 'root', 'root', '3306', '/tmp/mysql.sock');

Drupal
Drupal 需要增加一项为Unix_socket

最后还是推荐改PHP.ini配置,一劳永逸的事

HHVM

hhvm

$ brew install hhvm

安装Supervisord, 用于监控Supervisord并且可以自动重启hhvm当hhvm崩溃的时候

$ sudo easy_install supervisor
$ mkdir -p /usr/local/etc/supervisor.d/

PHP 错误处理

/**
 * Error.
 *
 * 3rd comonpent:
 *   filp/whoops
 *   monolog/monolog error log
 */

set_error_handler(function($errno, $errstr, $errfile, $errline, $errorcontext) {

  if(!(error_reporting() & $errno)) {
    return;
  }

  throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
});


var_dump($test);

PHP DatePeriod 周期

/**
 * DatePeriod
 *
 * 3rd component: https://github.com/briannesbitt/Carbon
 */


/**
 * DateInterval 表示到下一个周期的时间间隔.
 *
 * 2W表示两周.
 */
$interval = new DateInterval('P2W');
$start = new DateTime();

$periods = new DatePeriod($start, $interval, 3, DatePeriod::EXCLUDE_START_DATE);

foreach($periods as $nextDateTime) {
  var_dump($nextDateTime->format('Y-m-d'));
}

PHP Password Hashing

/**
* PHP Password
*
* author homepage: blog.ircmaxell.com
*
* Document: http://php.net/manual/zh/book.password.php
*/

/**
* generate
*/
$mypass = password_hash('mypassword', PASSWORD_DEFAULT, ['cost' => 12]);

/**
* validate.
*/
var_dump(password_verify('mypassword', $mypass));

面向对象进阶之:closure

/**
 * Class App
 *
 * 使用Closure bindTo实现路由添加.
 */
class App {
  protected $routers = [];
  protected $responseStatus = 200;
  protected $responseType = 'text/html';
  protected $responseBody = 'hello world';

  public function addRoute($routePath, Closure $routeCallback) {
    $this->routers[$routePath] = $routeCallback->bindTo($this, __CLASS__);
    return $this;
  }

  public function dispatch($currentPath = '') {
    if ($currentPath && isset($this->routers[$currentPath])) {
      $this->routers[$currentPath]();
    }

    header('HTTP/1.1 ' . $this->responseStatus);
    header('Content-type: ' . $this->responseType);
    header('Content-length: ' . mb_strlen($this->responseBody));
    print $this->responseBody;
  }

  public static function factory() {
    return new static();
  }
}

App::factory()->addRoute('home', function() {
  $this->responseBody = 'this is front page';
})->addRoute('news', function() {
  $this->responseBody = 'this is news page';
})->dispatch('news');