Laravel 开发笔记
Laravel 4.2 鉴权使用加盐密码
刚开始接触laravel,发现laravel默认的鉴权模块密码并未加盐处理(密码由password_hash方法创建)。所以自己琢磨着对密码加盐。像下面这样校验密码(密码在最初创建时,也以md5(salt . password .salt)的形式存储)
Auth::attempt(array('username'=>$user->username, 'password'=>$user->salt.Input::get('password').$user->salt))
但一直不成功,debug跟踪源码,可以看到最后,EloquentUserProvider的validateCredentials方法进一步调用BcryptHasher的check方法,,再进一步调用vendor/ircmaxell/password-compat/lib/password.php:230 password_verify方法,而不是我起初所想的直接$user->password == md5('input_password')。因此我在这里直接改写了源码,以此来实现密码加盐

Laravel 4.2 响应存在多余的空行
在任意响应中多四个空行,这个问题在4.2版本中遇到,并且在配置了auth过滤器的请求中才有

这个问题在下载请求时会有问题,比如压缩文件。在下载zip文件时,如果响应前步多几个空行,会造成文件起始多几个字节,造成这样的错误
warning [zip]: 8 extra bytes at beginning or within zipfile 。 因为代码文件里是windows 换行符 CRLF,所以四个空行是八个字符,所以响应头部多了八个字节

或者提示 该文件已损坏或者需要另一个压缩分卷
Laravel 5.3 清除客户端cookie
有时需要服务端来清除cookie,以保证所有httponly属性的cookie也能被清除。laravel已经提供API来生成清除cookie的http头


Laravel 5.3 实现controller路由
laravel 5.3中移出了controller路由,只保留了resources路由,这对开发规范的项目而言是好事,而对开发不规范的项目简直是灾难,开发不得不用get或者post路由为每一个控制器的方法注册路由,这会造成路由文件routes.php(routes/web.php)文件巨大不好维护。个人比较喜欢按约定来,所以写了个函数简单实现controller路由(约定namespace/controller/method)格式,如Home/XxYyController@getMmGg 将映射到 url : home/xx-yy/mm-gg,并且是get请求
/**
* 驼峰字符串转蛇形字符串
* @param $str
* @param string $delimiter
* @return string
*/
function humpToSnake($str,$delimiter = '_'){
if ( ! ctype_lower($str))
{
$replace = '$1'.$delimiter.'$2';
$str = strtolower(preg_replace('/([A-Za-z])([A-Z])/', $replace, $str));
}
return $str;
} /**
* 基于controller约定路由
* 例如: $namespace = 'H5'
* GET : XxYyController@getMmGg -> url : h5/xx-yy/mm-gg
* POST : XxYyController@postMmGg -> url : h5/xx-yy/mm-gg
* @param string $controller 控制器类名
* @param bool $namespace 相对于App\Http\Controllers的命名空间
*/
function routeController($controller,$namespace = false){
if (preg_match('/([\w]+)Controller$/', $controller, $matches))
{
$className = humpToSnake($matches[1],'-');
$methods = get_class_methods('App\Http\Controllers\\'.($namespace ? $namespace.'\\' : '').$controller);
foreach($methods as $method){
if(strpos($method,'get') === 0){
// 注册get路由
$methodName = humpToSnake(lcfirst(substr($method,3)),'-');
Route::get($className.'/'.$methodName,$controller.'@'.$method);
} else if(strpos($method,'post') === 0){
// 注册post路由
$methodName = humpToSnake(lcfirst(substr($method,4)),'-');
Route::post($className.'/'.$methodName,$controller.'@'.$method);
}
}
}
}
在php项目中独立使用Eloquent ORM框架
laravel使用的eloquent orm框架极其强大,大部分数据库层面的操作都能够在不写任何sql的情况下实现查询。所以在写其余项目时,比如爬虫,也想将此orm集成进来
eloquent 是一个独立的项目 https://github.com/illuminate/database,所以完全可以单独拿出来用
通过composer在项目中安装依赖
composer require illuminate/database:~4.2
将eloquent初始化的代码独立于一个php文件(start.php)中
<?php
/**
* Created by PhpStorm.
* User: lvyahui
* Date: 2016/3/17
* Time: 17:23
*/
require_once __DIR__ . '/vendor/autoload.php';
require_once 'config.php'; $localDBConf = config('db.local'); $database = array(
'driver' => 'mysql',
'host' => $localDBConf['host'],
'port' => $localDBConf['port'],
'database' => $localDBConf['name'],
'username' => $localDBConf['user'],
'password' => $localDBConf['pass'],
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
); //use Illuminate\Container\Container;
use Illuminate\Database\Capsule\Manager as Capsule; $capsule = new Capsule(); /*创建连接*/
$capsule->addConnection($database);
/*设置全局访问*/
$capsule->setAsGlobal();
/*启动Eloquent*/
$capsule->bootEloquent();
定义数据库模型 BaseModel.php
<?php
use Illuminate\Database\Eloquent\Model as Eloquent;
/**
* Created by PhpStorm.
* User: samlv
* Date: 2016/3/17
* Time: 17:30
*/
class BaseModel extends Eloquent
{
protected $guarded = array('id');
public $timestamps = false;
}
ApkClass.php
<?php
require_once ('BaseModel.php');
/**
* Created by PhpStorm.
* User: lvyahui
* Date: 2016/3/31
* Time: 16:35
*/
class ApkClass extends BaseModel
{
protected $table = 'apk_class';
}
在需要进行数据库操作中引入初始化文件和模型文件即可以使用
<?php
/**
* Created by PhpStorm.
* User: lvyahui
* Date: 2016/3/31
* Time: 17:00
* 扫描tmp/zip目录,解压左右的zip包,让后进行处理。
*/
require_once ('start.php');
require_once ('models/ApkClass.php'); foreach($usedApkClasss as $map_id=>$num){
ApkClass::where('map_id',$map_id)->update(array('num' => $num));
}
Laravel 基于约定进行子视图填充
laravel 另一个强大之处是其模板引擎,开发中常用的有两种,视图继承和子视图填充。这里以子视图填充为例,按约定的方式简化代码的编写
基础控制器
<?php use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Input;
class BaseController extends Controller
{ protected $layout = 'layouts.site'; protected $stdName = null; protected $routeParams = false;
/**
* Setup the layout used by the controller.
*
* @return void
*/
protected function setupLayout()
{
if ( ! is_null($this->layout))
{
$this->layout = View::make($this->layout);
}
} public function __construct()
{ } /**
* 获取控制器名称
* 例如:
* 类:admin/DataSourceController
* 将返回
* dataSource
* @return null|string
*/
public function getStdName()
{
if(!$this->stdName){
$className = get_class($this);
if (preg_match('/([\w]+)Controller$/', $className, $matches))
{
// $this->stdName = camel_case($matches[1]);
$this->stdName = lcfirst($matches[1]);
}
else
{
$this->stdName = $className;
}
}
return $this->stdName;
} public function makeView($data = array(),$view = null){
if(!$view){
$routeParams = $this->getRouteParams();
$controllerName = $routeParams['c'];
$methodName = $routeParams['m'];
if(preg_match('/^get(.*)$/',$methodName,$matches)){
$methodName = StringUtils::humpToSnake($matches[1]);
}
$view = $controllerName.'.'.$methodName;
}
if(!is_array($data)){
$data = array();
}
if(Request::ajax()){
return View::make($view,$data);
}else{
$this->layout->nest('content',$view,$data);
return false;
}
} /**
*
* @return array|bool
*/
public function getRouteParams(){
if(!$this->routeParams){ list($class,$method) = explode('@',Route::current()->getActionName());
$class = str_replace("\\",".",substr($class,0,strrpos($class,'Controller')));
// $names = explode(".",$class);
// foreach ($names as & $name) {
// $name = snake_case($name);
// }
$class = StringUtils::humpToSnake($class);
// $class = implode('.',$names); $this->routeParams = array(
'c' => $class,
'm' => $method
);
} return $this->routeParams;
} public function getRouteParam($key){
$routePatams = $this->getRouteParams();
return $routePatams[$key];
} }
控制器方法中只需要return makeView()方法即可,makeView方法会确定视图文件位置。
<?php class UserController extends BaseController
{
public function getList(){
return $this->makeView(array('users'=>array()));
}
}
主视图(site.blade.php)写法
<!DOCTYPE html>
<html lang="zh-CN">
<head>
@include('layouts.head')
<!-- 页面级别css -->
@yield('page.level.css','')
</head>
<body>
@include('layouts.header')
<div class="container-fluid">
{{$content}}
</div>
@include('layouts.footer')
<!-- 页面级别js文件 -->
@yield('page.level.js','')
<!-- 页面级别js代码片段 -->
@yield('page.level.script','')
</body>
</html>
上面几份代码实现这样的约定是:UserController@getList方法渲染views/user/list.blade.php页面,并将其填充到view/layouts/site.blade.php视图中,也就是我认为整个站点主视图(布局,layouts/site.blade.php)基本一致,所有方法产生的内容直接填充主视图即可,那以后开发新的页面或者接口,只需要按改约定开发即可
Laravel 开发笔记的更多相关文章
- Laravel学习笔记(三)--在CentOS上配置Laravel
在Laravel框架上开发了几天,不得不说,确实比较优雅,处理问题逻辑比较清楚. 今天打算在CentOS 7上配置一个Laravel,之前都是在本机上开发,打算实际配置一下. 1)系统 ...
- Laravel学习笔记之Session源码解析(上)
说明:本文主要通过学习Laravel的session源码学习Laravel是如何设计session的,将自己的学习心得分享出来,希望对别人有所帮助.Laravel在web middleware中定义了 ...
- Laravel学习笔记之PHP反射(Reflection) (上)
Laravel学习笔记之PHP反射(Reflection) (上) laravel php reflect 2.1k 次阅读 · 读完需要 80 分钟 3 说明:Laravel中经常使用PHP的反 ...
- [开发笔记]-未找到与约束ContractName Microsoft.VisualStudio.Text.ITextDocumentFactoryService...匹配的导出【转载自:酷小孩】
原文地址:http://www.cnblogs.com/babycool/p/3199158.html 今天打算用VisualStudio2012做一个js效果页面测试的时候,打开VS2012新建项目 ...
- EasyUI 开发笔记(二)
接上篇 :EasyUI 开发笔记(一) (http://www.cnblogs.com/yiayi/p/3485258.html) 这期就简单介绍下, easyui 的 list 展示, 在easy ...
- EasyUI 开发笔记(一)
由于某些原因,在公司做的后台需要改成类似于Ext.js 形式的后台,主要看好其中的 框架布局,以及tab开页面和弹出式内部窗体. 后来看看,改成EasyUI,较Ext.js 库小很多,也便于公司的初级 ...
- [Openwrt 项目开发笔记]:Openwrt平台搭建(一)
[Openwrt项目开发笔记]系列文章传送门:http://www.cnblogs.com/double-win/p/3888399.html 正文: 最近开始着手进行Openwrt平台的物联网网关设 ...
- Android移动APP开发笔记——Cordova(PhoneGap)通过CordovaPlugin插件调用 Activity 实例
引言 Cordova(PhoneGap)采用的是HTML5+JavaScript混合模式来开发移动手机APP,因此当页面需要获取手机内部某些信息时(例如:联系人信息,坐标定位,短信等),程序就需要调用 ...
- Android移动APP开发笔记——最新版Cordova 5.3.1(PhoneGap)搭建开发环境
引言 简单介绍一下Cordova的来历,Cordova的前身叫PhoneGap,自被Adobe收购后交由Apache管理,并将其核心功能开源改名为Cordova.它能让你使用HTML5轻松调用本地AP ...
随机推荐
- windows apache 开启 GZIP
从服务端优化来说,通过对服务端做压缩配置可以大大减小文本文件的体积,从而使加载文本的速度成倍的加快.目前比较通用的压缩方法是启用gzip压缩.它 会把浏览器请求的页面,以及页面中引用的静态资源以压缩包 ...
- InnoDB的表类型,逻辑存储结构,物理存储结构
表类型 对比Oracle支持的各种表类型,InnoDB存储引擎表更像是Oracle中的索引组织表(index organized table).在InnoDB存储引擎表中,每张表都有个主键,如果在创建 ...
- FMS中实现pull stream
//程序启动时执行 application.onAppStart = function() { this.myNC= new NetConnection(); this.myNC.onStatus = ...
- 关于redis的主从、哨兵、集群
关于redis主从.哨兵.集群的介绍网上很多,这里就不赘述了. 一.主从 通过持久化功能,Redis保证了即使在服务器重启的情况下也不会损失(或少量损失)数据,因为持久化会把内存中数据保存到硬盘上,重 ...
- HDU5726(RMQ&&二分)
GCD Time Limit:5000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u Submit Status D ...
- 在线office文档编辑NTKO使用心得
目录 前言 什么是ntko 准备工作 实战演练 总结 一.前言 Web开发中经常需要用到在线处理office文档的功能,现在市面上有一些常用的Web页面调用显示Office的控件技术,用起来很方便.有 ...
- [CSS3] 学习笔记-选择器详解(二)
1.选择器first-child.last-child.nth-child和nth-last-child 利用first-child.last-child.nth-child和nth-last-chi ...
- form表单的两种提交方式,submit和button的用法
1.当输入用户名和密码为空的时候,需要判断.这时候就用到了校验用户名和密码,这个需要在jsp的前端页面写:有两种方法,一种是用submit提交.一种是用button提交.方法一: 在jsp的前端页面的 ...
- SVN-TortoiseSVN安装和常用操作步骤
安装VisualSVN-Server-2.0.5 服务端: 运行VisualSVN-Server-2.0.5.msi程序,点击Next,下面的截图顺序即为安装步骤: 2 图2: 注意:Server P ...
- Struts2的概述和入门
忽如一夜春风来,千树万树梨花开 上节我们说到,JAVAEE的三层架构,即web层,service层,dao层.hibernate是应用在dao层的.而我们现在所学的Struts2是应用在web层.St ...