Many developers using Laravel may have only scratched the surface of what the framework has to offer. While the documentation does cover the most common use cases and obvious features, it doesn't cover everything.
Don't get me wrong, the documentation is great, it's just that there are so many things you can do that it's hard to document everything. So, we’re going to take a look at some of the hidden gems lurking in Laravel.
Available time: v4.0.0
Record:No
Views can be cascaded like configuration files. Cascading views are very useful when developing scalable theming systems. Consider the following directory structure.
/app /views /blog /index.blade.php /themes /default /views /blog /index.blade.php /theme.blade.php
The idea is that when we return View::make('theme::blog.index');
it will first be in the themes/default/views
directory Search, find the view if not found, fall back to app/views
.
To do this, we use View::addNamespace
to register our own namespace in both locations.
View::addNamespace('theme', [ base_path().'/themes/default/views', app_path().'/views' ]);
Available time: v4.0.0
Record:Part
Collections are a great way to interact with and manage arrays. Collections have a variety of convenience methods and implement many useful interfaces, such as ArrayableInterface
, IteratorAggregate
, and JsonableInterface
.
Suppose we are building a small blog engine that uses flat files for storage. We want to be able to perform operations such as sorting, filtering, and paging.
Implementing a blog engine is beyond the scope of this article, but assume we have an array $articles
, and each member of the array is an instance of the Article
class. Then all we need to do is get a new instance of Collection
and give it our array of articles.
$articles = new Illuminate\Support\Collection($arrayOfArticles);
Using collections we can sort articles. Let’s sort the articles and display the most recently updated ones first. For the purposes of this article, we assume that when loading an article from the file system, we set the updatedAt
attribute to the last modification time of the file.
$articles->sortByDesc(function ($article) { return $article->updatedAt; });
sortBy
and sortByDesc
methods accept a callback that should return a value that can be used to sort the collection. In our case, we can simply return the last modification time of the article, and the collection can be sorted based on that time.
Similar to sorting, we can also use collections to filter our articles, just like the WHERE
clause in MySQL. Let's filter our articles based on searches that may have been run.
<?php $searchQuery = 'Laravel rocks!'; $results = $articles->filter(function ($article) use ($searchQuery) { return preg_match(sprintf('/%s/m', $searchQuery), $article->body); });
filter
method actually returns a new instance of Illuminate\Support\Collection
, so we need to assign it to the $results
variable. This new collection will only contain articles that mention "Laravel rock!"
Using this collection, we can paginate articles so that there are not too many articles on a single page.
$perPage = 1; $page = Input::get('page', 1); if ($page > ($articles->count() / $perPage)) { $page = 1; } $pageOffset = ($page * $perPage) - $perPage; $results = $articles->slice($pageOffset, $perPage);
Using the slice
method, we extract a portion of the articles in the collection and assign it to the $results
variable.
This example can be further implemented by creating a new instance of Laravel's Paginator
class. This way it can generate all the page numbers and links for you.
We can get a random article:
$article = $articles->random();
We can also iterate over our collection of articles as if it were a regular array. This is all thanks to the IteratorAggregate
and ArrayIterator
interfaces.
foreach ($articles as $article) { echo $article->body; }
We can even convert articles to regular arrays or their JSON representation.
$array = $articles->toArray(); $json = $articles->toJson();
One of the coolest methods is probably groupBy
, which allows us to group articles by a specific key. Imagine that each article has some metadata at the top that is parsed and removed from the article body.
Although parsing this metadata is beyond the scope of this article, we assume it is parsed and is a property on the Article
instance. You can then use groupBy
to group the articles by the category they were published in.
$results = $articles->groupBy('category');
All articles sharing the same category will be grouped. Then you can get articles in a specific category.
foreach ($results->get('tutorial') as $article) { echo $article->body; }
Collections are one of the best hidden gems Laravel has to offer.
Available time: v4.1.19
Record:No
Filtering routes in Laravel is a common task that many of us perform in all our projects. Filters allow you to perform tasks such as user authentication or rate limiting before or after a route is triggered. We create filters using Route::filter
and can apply them to individual routes, route groups, or use Route::when
and apply to matching patterns.
Route::filter('restricted', function($route, $request, $group) { // Restrict user access based on the value of $group }); Route::when('admin/*', 'restricted:admin');
在此示例中,我们创建一个 restricted
过滤器,它需要一个参数 $group
。 $route
和 $request
参数始终提供给 before 过滤器。
但是如果我们想要更大的灵活性怎么办?假设我们想要将过滤器应用于所有 admin
路由除了 admin/login
。我们可以使用路线组并将相关路线移至组外。或者我们可以使用 Route::whenRegex
并编写我们自己的正则表达式。
Route::whenRegex('/^admin(\/(?!login)\S+)?$/', 'restricted:admin');
此正则表达式只是确保它仅适用于以 admin
开头且后面不跟 /login
的路由,但后面可以跟任何其他内容。出色的。现在,我们将 restricted:admin
过滤器应用于除 admin/login
路由之外的所有路由。
可用时间: v4.0.0
记录:部分
毫无疑问,您已经使用 Illuminate\Support\MessageBag
一段时间了,甚至没有意识到。 MessageBag
扮演的最大角色是在使用 Laravel 内置验证器时包含所有验证错误。
每个视图中都有一个$errors
变量,该变量包含空的MessageBag
实例或使用Redirect::to('/')->withErrors($validator);
刷新到会话的实例
当在特定输入下方显示错误消息时,很多人可能会在表单中执行类似的操作。
{{ Form::text('username', null) }} @if($errors->has('username')) <div class="error">{{ $errors->first('username') }}></div>; @endif
您实际上可以完全删除 if
语句,并使用 first
方法的第二个参数将消息包装在 div
中。
{{ Form::text('username', null) }} {{ $errors->first('username', '<div class="error">:message</div>') }}
好多了,好多了!
可用时间: v3.0.0
记录:部分
Fluent
类已经存在很长时间了,当使用模式生成器创建迁移时,它实际上在框架本身内使用。 Laravel 3 和 Laravel 4 之间,类本身几乎没有变化,唯一大的区别是多了一些接口。
要使用 Fluent
类,您所需要做的就是获取一个实例,然后就可以了。
$user = new Illuminate\Support\Fluent; $user->name('Jason')->country('Australia')->subscriber();
该实例现在定义了 3 个属性:name
,值为 Jason
、country
,值为 Australia
和 subscriber
,值为布尔值 true
。
在 Laravel 4.1 之前,您只能从实例中真正设置和获取属性。从 Laravel 4.1 开始,您可以使用 toArray
和 toJson
方法分别获取属性数组及其 JSON 表示形式。
从 Laravel 4.2 开始,该类还实现了 JsonSerialized
接口,这意味着您可以将实例直接传递到 json_encode
中。
我们已经研究了 Laravel 框架的几个有用的精华。但是,正如您所猜测的,框架内还有更多内容。
了解 Laravel 可能提供的其他功能的最佳方法是深入研究源代码。它并不像您想象的那么可怕,您将学到很多关于您正在构建的框架的知识。
如果您发现了其他宝石,请随时在评论中分享!
The above is the detailed content of Uncover Laravel's Hidden Treasures. For more information, please follow other related articles on the PHP Chinese website!