Skip to main content

PHP

Tips#

# CentOS# 查看安装文件rpm -ql php-fpmyum instal yum-utils# 查看已安装的文件repoquery -lq --installed time
# 內建 web 服务# http://php.net/manual/zh/features.commandline.webserver.phpphp -S 0.0.0.0:8082 -c php.ini
# 判断是否有响应模块php -i "(command-line 'phpinfo()')" | grep -i grpc
# PHP 常用配置date.timezone=Asia/Shanghai

Docker#

# wener/php:app# php7 + nginx + mongo,redis,grpc extension + composerdocker run --rm -it --entrypoint bash wener/php:app

PHP 7#

  • opcache

laravel#

# 可使用代理 https_proxy=http://127.0.0.1:7777 http_proxy=http://127.0.0.1:7777composer global require -vvv "laravel/lumen-installer"composer create-project --prefer-dist laravel/lumen  -vvv blogcd blogphp -S localhost:8000 -t ./public
php artisan make:migration create_users_table# 修改 Mirage 下的数据,添加 User 表的 migrate# 添加 UserTableSeeder 往 User 插入数据php artisan migrate# 可以回滚php artisan migrate:rollback# 调用 seederphp artisan db:seed

Lumen#

  • Laravel Lumen
    • The stunningly fast micro-framework by Laravel.
  • 主要做 REST 服务

CentOS#

# 7.xrpm -Uvh https://mirror.webtatic.com/yum/el7/epel-release.rpmrpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm# 该仓库中的内容可以查看 https://uk.repo.webtatic.com/yum/el7/SRPMS/RPMS/# 现在可以直接安装 56 版本yum install php56w php56w-opcache# 也可以使用插件来替换本地的 php 版本yum install yum-plugin-replaceyum replace --enablerepo=webtatic-testing php-common --replace-with=php56w-common

Composer#

# 使用中国镜像安装php -r "copy('https://install.phpcomposer.com/installer', 'composer-setup.php');" && \php composer-setup.php && \php -r "unlink('composer-setup.php');" && \mv composer.phar /usr/local/bin/composer
# 使用国内镜像# 修改全局配置composer config -g repo.packagist composer https://packagist.phpcomposer.com# 修改当前项目composer config repo.packagist composer https://packagist.phpcomposer.com

# 初始化composer init# 添加依赖composer require paquettg/php-html-parser# 移除依赖composer remove paquettg/php-html-parser# 安装依赖composer install# 更新依赖composer updatecomposer update --lockcomposer dump-autoload --optimize

composer aboutcomposer archivecomposer browsecomposer clear-cachecomposer config --listcomposer create-project symfony/standard-edition dir/composer depends vendor-name/package-namecomposer diagnosecomposer globalcomposer helpcomposer initcomposer licensescomposer listcomposer removecomposer run-scriptcomposer search my keywordscomposer self-updatecomposer showcomposer suggestcomposer statuscomposer validate
  • 安装好后只需要添加一下 autoload 即可使用
<?phprequire __DIR__ . '/vendor/autoload.php';

satis#

# 可以映射主机上的主目录以利用缓存# -v $COMPOSER_HOME:/composerdocker run --rm -it -v $PWD/build:/build --entrypoint /bin/sh composer/satis
# 当构建完成后直接上传为静态站点即可rsync -avz  build/ my-server:/var/www/html

satis.json

{    "name": "MyRepo",    "homepage": "https://composer.example.org",    "repositories": [{            "type": "vcs",            "url": "https://example.org/code/api-php.git"        },        {            "type": "vcs",            "url": "https://example.org/code/other-php.git"        }    ],    "require-all": true}
cd /build# 创建 satis.jsonphp /satis/bin/satis build satis.json .# 或者 docker 构建docker run --rm -it -v $PWD/build:/build composer/satisrsync -avz --delete ./build/ [email protected]:/mysite

ThinkPHP5#

composer create-project topthink/think tp5  --prefer-distcd tp5

# 启动自带 web 服务器php -S localhost:8888 application/route.php
# 使得 think 可执行# 不操作这一步也可以直接使用 php think 来执行chmod +x think# 查看所有命令./think list# Available commands:#   build              Build Application Dirs#   clear              Clear runtime file#   help               Displays help for a command#   list               Lists commands#  make#   make:controller    Create a new resource controller class#   make:model         Create a new model class#  optimize#   optimize:autoload  Optimizes PSR0 and PSR4 packages to be loaded with classmaps too, good for production.#   optimize:config    Build config and common file cache.#   optimize:route     Build route cache.#   optimize:schema    Build database schema cache.
# 生成定义的文件# 默认会使用 application/build.php./think build# 使用指定的配置文件./think build --config build.php

目录结构#

project  应用部署目录├─application           应用目录(可设置)│  ├─common             公共模块目录(可更改)│  ├─index              模块目录(可更改)│  │  ├─config.php      模块配置文件│  │  ├─common.php      模块函数文件│  │  ├─controller      控制器目录│  │  ├─model           模型目录│  │  ├─view            视图目录│  │  └─ ...            更多类库目录│  ├─command.php        命令行工具配置文件│  ├─common.php         应用公共(函数)文件│  ├─config.php         应用(公共)配置文件│  ├─database.php       数据库配置文件│  ├─tags.php           应用行为扩展定义文件|  ├─build.php          自动生成定义文件│  └─route.php          路由配置文件├─extend                扩展类库目录(可定义)├─public                WEB 部署目录(对外访问目录)│  ├─static             静态资源存放目录(css,js,image)│  ├─index.php          应用入口文件│  ├─router.php         快速测试文件│  └─.htaccess          用于 apache 的重写├─runtime               应用的运行时目录(可写,可设置)├─vendor                第三方类库目录(Composer)├─thinkphp              框架系统目录│  ├─lang               语言包目录│  ├─library            框架核心类库目录│  │  ├─think           Think 类库包目录│  │  └─traits          系统 Traits 目录│  ├─tpl                系统模板目录│  ├─.htaccess          用于 apache 的重写│  ├─.travis.yml        CI 定义文件│  ├─base.php           基础定义文件│  ├─composer.json      composer 定义文件│  ├─console.php        控制台入口文件│  ├─convention.php     惯例配置文件│  ├─helper.php         助手函数文件(可选)│  ├─LICENSE.txt        授权说明文件│  ├─phpunit.xml        单元测试配置文件│  ├─README.md          README 文件│  └─start.php          框架引导文件├─build.php             自动生成定义文件(参考)├─composer.json         composer 定义文件├─LICENSE.txt           授权说明文件├─README.md             README 文件├─think                 命令行入口文件

代码#

  • thinkphp/start.php

    • 系统默认的一个引导文件
    • 加载系统常量定义
    • 加载环境变量定义文件
    • 注册自动加载机制
    • 注册错误和异常处理机制
    • 加载惯例配置文件
    • 执行应用
    • 首先会调用base.php基础引导文件,某些特殊需求下面可能直接在入口文件中引入基础引导文件。
  • 路由

    • __miss__ 定义未找到时的操作
    • [blog] 分组使用 [] 标示
  • 控制器

    • 标准控制器支持 请求方法+路径 的转换
    • 资源控制支持以下方法映射
    标识请求类型生成路由规则对应操作方法(默认)
    indexGETblogindex
    createGETblog/createcreate
    savePOSTblogsave
    readGETblog/:idread
    editGETblog/:id/editedit
    updatePUTblog/:idupdate
    deleteDELETEblog/:iddelete
  • 模型

    • 支持数据库表映射
    • 支持基本的增删改查操作

PECL#

pecl updahe-channels# yes 启用 igbinary# https://github.com/igbinary/igbinarypecl install -o -f redis <<<no
build                  Build an Extension From C Sourcebundle                 Unpacks a Pecl Packagechannel-add            Add a Channelchannel-alias          Specify an alias to a channel namechannel-delete         Remove a Channel From the Listchannel-discover       Initialize a Channel from its serverchannel-info           Retrieve Information on a Channelchannel-login          Connects and authenticates to remote channel serverchannel-logout         Logs out from the remote channel serverchannel-update         Update an Existing Channelclear-cache            Clear Web Services Cacheconfig-create          Create a Default configuration fileconfig-get             Show One Settingconfig-help            Show Information About Settingconfig-set             Change Settingconfig-show            Show All Settingsconvert                Convert a package.xml 1.0 to package.xml 2.0 formatcvsdiff                Run a "cvs diff" for all files in a packagecvstag                 Set CVS Release Tagdownload               Download Packagedownload-all           Downloads each available package from the default channelinfo                   Display information about a packageinstall                Install Packagelist                   List Installed Packages In The Default Channellist-all               List All Packageslist-channels          List Available Channelslist-files             List Files In Installed Packagelist-upgrades          List Available Upgradeslogin                  Connects and authenticates to remote server [Deprecated in favor of channel-login]logout                 Logs out from the remote server [Deprecated in favor of channel-logout]makerpm                Builds an RPM spec file from a PEAR packagepackage                Build Packagepackage-dependencies   Show package dependenciespackage-validate       Validate Package Consistencypickle                 Build PECL Packageremote-info            Information About Remote Packagesremote-list            List Remote Packagesrun-scripts            Run Post-Install Scripts bundled with a packagerun-tests              Run Regression Testssearch                 Search remote package databaseshell-test             Shell Script Testsign                   Sign a package distribution filesvntag                 Set SVN Release Taguninstall              Un-install Packageupdate-channels        Update the Channel Listupgrade                Upgrade Packageupgrade-all            Upgrade All Packages [Deprecated in favor of calling upgrade with no parameters]Usage: pecl [options] command [command-options] <parameters>Type "pecl help options" to list all options.Type "pecl help shortcuts" to list all command shortcuts.Type "pecl help version" or "pecl version" to list version information.Type "pecl help <command>" to get the help for the specified command.

HHVM#

Symfony#

Notes#

  • require,require_once,include_once,include 是语句而不是函数, 所以不需要括号 ()

FAQ#

避免直接访问 PHP#

<?php// 避免不被 includeif(count(get_included_files()) ==1) exit("Direct access not permitted.");
// 避免被 includefunction blockit(){  $buf = get_included_files();  return $buf[0] != __FILE__;}blockit() and exit("You can not include a MAIN file as a part of your script.");

确保相对引用正确#

<?php // 定义相对路径define('__ROOT__', dirname(dirname(__FILE__)));require_once(__ROOT__.'/config.php'); 
// 而不是使用绝对路径require_once('/var/www/public_html/config.php'); ?> 

查看 ca 环境#

php -r "print_r(openssl_get_cert_locations());" 

Connection to `ssl://pecl.php.net:443' failed: Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP?#

  • 可能是由于未启用 openssl php -m | grep ssl
  • 可能是由于 pecl 未加载 php.ini
# 设置 php.inipear config-set php_ini /etc/php7/php.ini