escapework / laravelhelpers
一些Laravel 4辅助工具,以享受更丰富的开发体验
Requires
- php: >=5.4.0
Requires (Dev)
- illuminate/database: >=4.1.0
- illuminate/support: >=4.1.0
- illuminate/validation: >=4.1.0
- phpspec/phpspec: ~2.0
README
一套工具和辅助类,用于帮助Laravel 4开发。
安装
通过 Composer 安装。
{ "require": { "escapework/laravelhelpers": "0.7.*" } }
模型
为了充分利用LaravelHelpers中的最佳功能,请确保您的所有模型都扩展了BaseModel
类。
use EscapeWork\LaravelHelpers\BaseModel; class Product extends BaseModel { // ... }
别名
如果您需要为模型生成别名,只需使用SluggableTrait
;
use EscapeWork\LaravelHelpers\BaseModel; use EscapeWork\LaravelHelpers\SluggableTrait; class Product extends BaseModel { use SluggableTrait; }
在执行save
和update
方法时,辅助类将自动生成别名。
默认的别名是通过title
属性生成的。但如果有不同的属性,只需声明$sluggableAttr
字段名。
protected $sluggableAttr = 'name';
如果您不想在更新模型时更改别名,请在模型上设置$makeSlugOnUpdate
属性。
protected $makeSlugOnUpdate = false;
然后,就像使用模型一样使用它
public function store() { $this->product->title = 'Hello World'; $this->product->save(); echo $this->product->slug; // prints hello-world } }
搜索
要搜索多个术语,可以使用scopeSearch
方法。
$products = $product->search('title', 'this title')->get();
这将转换SQL语句
select * from products where title regexp 'this.+title'
设置器
LaravelHelpers的BaseModel
有两个设置器方法来帮助您
_setDateAttribute
// model ... public function setDateAttribute($date) { $this->_setDateAttribute('date', $date, $format = 'd/m/Y'); } ... // whaterer place you need $model->date = '10/03/1991'; // this format should be the same as the above
如果一切正常,$model->date
将是一个Carbon
实例。否则,$model->date
将为null。
_setCurrencyAttribute
// model ... public function setPriceBRLAttribute($price) { $this->_setCurrencyAttribute('priceBRL', $price); } public function setPriceAttribute($price) { $this->_setCurrencyAttribute('price', $price, 'USD'); } ... // whaterer place you need $model->priceBRL = '10,90'; $model->price = '10.90'; var_dump($model->priceBRL); // (float) 10.90'; var_dump($model->price); // (float) 10.90';
如果一切正常,将设置一个float
值。否则,值将为null。
组合框
LaravelHelpers有一个方法,用于在使用Form
类时简化创建组合框。
Form::select('product_id', Product::all()->combobox());
选项文本的默认属性是title
属性。如果您需要其他字段,只需像这样使用即可
Form::select('client_id', Client::all()->combobox(['field' => 'name']); // for using the 'name' field
如果您想创建一个“空”选项,可以这样做
Form::select('client_id', Client::all()->combobox(['field' => 'name', 'empty_option' => true, 'empty_option_label' => 'Select a client']));
以下文档适用于版本0.6
,因此现在并非所有内容都相同。
查找或失败
$product = App::make('ProductRepository'); // just a sample, you probably will use dependency injection $product->findOrFailBy('slug', 'office-chair'); dd($product->title);
如果找不到产品,则将抛出Illuminate\Database\Eloquent\ModelNotFoundException
,就像Eloquent函数findOrFail
一样。
许可证
MIT许可证 (MIT)
版权所有 (c) 2013 Escape Criativação LTDA
特此免费授予任何获得此软件及其相关文档文件(“软件”)副本的任何人(“许可人”)处理软件的权利,不受限制,包括但不限于使用、复制、修改、合并、发布、分发、再许可和/或出售软件副本的权利,并允许获得软件的人这样做,但须遵守以下条件
上述版权声明和本许可声明应包含在软件的所有副本或实质性部分中。
本软件按“原样”提供,不提供任何明示或暗示的保证,包括但不限于适销性、适用于特定目的和无侵权性的保证。在任何情况下,作者或版权所有者均不对任何索赔、损害或其他责任负责,无论是基于合同、侵权或其他方式,源于、涉及或与软件或其使用或其他交易有关。