PHP开发宝典-PHP基础
- - CSDN博客推荐文章.
-->//包含库
include 'dispatch.php';
// 定义你的路由
get('/greet', function () {
//渲染视图
render('greet-form');
});
//post处理
post('/greet', function () {
$name = from($_POST, 'name');
// render a view while passing some locals
render('greet-show', array('name' => $name));
});
// serve your site
dispatch();
respond('/[:name]', function ($request) {
echo 'Hello ' . $request->name;
});
respond('GET', '/posts', $callback);
respond('POST', '/posts/create', $callback);
respond('PUT', '/posts/[i:id]', $callback);
respond('DELETE', '/posts/[i:id]', $callback);
//匹配多种请求方法:
respond(array('POST','GET'), $route, $callback);
//你或许也想在相同的地方处理请求
respond('/posts/[create|edit:action] /[i:id] ', function ($request, $response) {
switch ($request->action) {
// do something
}
});
require '../ham/ham.php';
$app = new Ham('example');
$app->config_from_file('settings.php');
$app->route('/pork', function($app) {
return "Delicious pork.";
});
$hello = function($app, $name='world') {
return $app->render('hello.html', array(
'name' => $name
));
};
$app->route('/hello/<string>', $hello);
$app->route('/', $hello);
$app->run();
use Assetic\Asset\AssetCollection;
use Assetic\Asset\FileAsset;
use Assetic\Asset\GlobAsset;
$js = new AssetCollection(array(
new GlobAsset('/path/to/js/*'),
new FileAsset('/path/to/another.js'),
));
//当资源被输出时,代码会被合并
echo $js->dump();
// 从norway.jpg图片初始化norway层
$norwayLayer = ImageWorkshop::initFromPath('/path/to/images/norway.jpg');
// 从watermark.png图片初始化watermark层(水印层)
$watermarkLayer = ImageWorkshop::initFromPath('/path/to/images/watermark.png');
$image = $norwayLayer->getResult(); // 这是生成的图片!
header('Content-type: image/jpeg');
imagejpeg($image, null, 95); // We choose to show a JPG with a quality of 95%
exit;
require_once '/path/to/snappy/src/autoload.php';
use Knp\Snappy\Pdf;
//通过wkhtmltopdf binary路径初始化库
$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
//通过把Content-type头设置为pdf来在浏览器中展示pdf
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="file.pdf"');
echo $snappy->getOutput('http://www.github.com');
$user = ORM::for_table('user')
->where_equal('username', 'j4mie')
->find_one();
$user->first_name = 'Jamie';
$user->save();
$tweets = ORM::for_table('tweet')
->select('tweet.*')
->join('user', array(
'user.id', '=', 'tweet.user_id'
))
->where_equal('user.username', 'j4mie')
->find_many();
foreach ($tweets as $tweet) {
echo $tweet->text;
}
__::each(array(1, 2, 3), function($num) { echo $num . ','; }); // 1,2,3,
$multiplier = 2;
__::each(array(1, 2, 3), function($num, $index) use ($multiplier) {
echo $index . '=' . ($num * $multiplier) . ',';
});
// prints: 0=2,1=4,2=6,
__::reduce(array(1, 2, 3), function($memo, $num) { return $memo + $num; }, 0); // 6
__::find(array(1, 2, 3, 4), function($num) { return $num % 2 === 0; }); // 2
__::filter(array(1, 2, 3, 4), function($num) { return $num % 2 === 0; }); // array(2, 4)
$headers = array('Accept' => 'application/json');
$options = array('auth' => array('user', 'pass'));
$request = Requests::get('https://api.github.com/gists', $headers, $options);
var_dump($request->status_code);
// int(200)
var_dump($request->headers['content-type']);
// string(31) "application/json; charset=utf-8"
var_dump($request->body);
// string(26891) "[…]"
$request = new Buzz\Message\Request('HEAD', '/', 'http://google.com');
$response = new Buzz\Message\Response();
$client = new Buzz\Client\FileGetContents();
$client->send($request, $response);
echo $request;
echo $response;
require_once '/path/to/goutte.phar';
use Goutte\Client;
$client = new Client();
$crawler = $client->request('GET', 'http://www.symfony-project.org/');
//点击链接
$link = $crawler->selectLink('Plugins')->link();
$crawler = $client->click($link);
//使用一个类CSS语法提取数据
$t = $crawler->filter('#data')->text();
echo "Here is the text: $t";
printf("Right now is %s", Carbon::now()->toDateTimeString());
printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver'));
$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();
$nextSummerOlympics = Carbon::createFromDate(2012)->addYears(4);
$officialDate = Carbon::now()->toRFC2822String();
$howOldAmI = Carbon::createFromDate(1975, 5, 21)->age;
$noonTodayLondonTime = Carbon::createFromTime(12, 0, 0, 'Europe/London');
$endOfWorld = Carbon::createFromDate(2012, 12, 21, 'GMT');
//总是以UTC对比
if (Carbon::now()->gte($endOfWorld)) {
die();
}
if (Carbon::now()->isWeekend()) {
echo 'Party!';
}
echo Carbon::now()->subMinutes(2)->diffForHumans(); // '2分钟之前'
use Ubench\Ubench; $bench = new Ubench; $bench->start(); //执行一些代码 $bench->end(); //获取执行消耗时间和内存 echo $bench->getTime(); // 156ms or 1.123s echo $bench->getTime(true); // elapsed microtime in float echo $bench->getTime(false, '%d%s'); // 156ms or 1s echo $bench->getMemoryPeak(); // 152B or 90.00Kb or 15.23Mb echo $bench->getMemoryPeak(true); // memory peak in bytes 内存峰值 echo $bench->getMemoryPeak(false, '%.3f%s'); // 152B or 90.152Kb or 15.234Mb //在结束标识处返回内存使用情况 echo $bench->getMemoryUsage(); // 152B or 90.00Kb or 15.23Mb
use Respect\Validation\Validator as v;
//简单验证
$number = 123;
v::numeric()->validate($number); //true
//链式验证
$usernameValidator = v::alnum()->noWhitespace()->length(1,15);
$usernameValidator->validate('alganet'); //true
//验证对象属性
$user = new stdClass;
$user->name = 'Alexandre';
$user->birthdate = '1987-07-01';
//在一个简单链中验证他的属性
$userValidator = v::attribute('name', v::string()->length(1,32))
->attribute('birthdate', v::date()->minimumAge(18));
$userValidator->validate($user); //true
$f = Filter::factory('string,max:5');
$str = 'This is a test string';
$f->validate($str); // false
$f->filter($str); // 'This '
//引用Faker 自动加载器 require_once '/path/to/Faker/src/autoload.php'; //使用工厂创建来创建一个Faker\Generator实例 $faker = Faker\Factory::create(); //通过访问属性生成假数据 echo $faker->name; // 'Lucy Cechtelar'; echo $faker->address; // "426 Jordy Lodge // Cartwrightshire, SC 88120-6700" echo $faker->text; // Sint velit eveniet. Rerum atque repellat voluptatem quia ...
$m = new Mustache_Engine;
echo $m->render('Hello {{planet}}', array('planet' => 'World!')); // "Hello World!"
use Gaufrette\Filesystem;
use Gaufrette\Adapter\Ftp as FtpAdapter;
use Gaufrette\Adapter\Local as LocalAdapter;
//本地文件:
$adapter = new LocalAdapter('/var/media');
//可选地使用一个FTP适配器
// $ftp = new FtpAdapter($path, $host, $username, $password, $port);
//初始化文件系统
$filesystem = new Filesystem($adapter);
//使用它
$content = $filesystem->read('myFile');
$content = 'Hello I am the new content';
$filesystem->write('myFile', $content);
use Omnipay\CreditCard;
use Omnipay\GatewayFactory;
$gateway = GatewayFactory::create('Stripe');
$gateway->setApiKey('abc123');
$formData = ['number' => '4111111111111111', 'expiryMonth' => 6, 'expiryYear' => 2016];
$response = $gateway->purchase(['amount' => 1000, 'card' => $formData]);
if ($response->isSuccessful()) {
//支付成功:更新数据库
print_r($response);
} elseif ($response->isRedirect()) {
//跳转到异地支付网关
$response->redirect();
} else {
//支付失败:向客户显示信息
exit($response->getMessage());
}
$storage = new \Upload\Storage\FileSystem('/path/to/directory');
$file = new \Upload\File('foo', $storage);
//验证文件上传
$file->addValidations(array(
//确保文件类型是"image/png"
new \Upload\Validation\Mimetype('image/png'),
//确保文件不超过5M(使用"B","K","M"或者"G")
new \Upload\Validation\Size('5M')
));
//试图上传文件
try {
//成功
$file->upload();
} catch (\Exception $e) {
//失败!
$errors = $file->getErrors();
}
require_once '/path/to/HTMLPurifier.auto.php'; $config = HTMLPurifier_Config::createDefault(); $purifier = new HTMLPurifier($config); $clean_html = $purifier->purify($dirty_html);
use MischiefCollective\ColorJizz\Formats\Hex;
$red_hex = new Hex(0xFF0000);
$red_cmyk = $hex->toCMYK();
echo $red_cmyk; // 0,1,1,0
echo Hex::fromString('red')->hue(-20)->greyscale(); // 555555
use Location\Coordinate; use Location\Distance\Vincenty; $coordinate1 = new Coordinate(19.820664, -155.468066); // Mauna Kea Summit 茂纳凯亚峰 $coordinate2 = new Coordinate(20.709722, -156.253333); // Haleakala Summit $calculator = new Vincenty(); $distance = $calculator->getDistance($coordinate1, $coordinate2); // returns 128130.850 (meters; ≈128 kilometers)
require 'ShellWrap.php';
use \MrRio\ShellWrap as sh;
//列出当前文件下的所有文件
echo sh::ls();
//检出一个git分支
sh::git('checkout', 'master');
//你也可以通过管道把一个命令的输出用户另一个命令
//下面通过curl跟踪位置,然后通过grep过滤'html'管道来下载example.com网站
echo sh::grep('html', sh::curl('http://example.com', array(
'location' => true
)));
//新建一个文件
sh::touch('file.html');
//移除文件
sh::rm('file.html');
//再次移除文件(这次失败了,然后因为文件不存在而抛出异常)
try {
sh::rm('file.html');
} catch (Exception $e) {
echo 'Caught failing sh::rm() call';
}