Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Laracasts Widgets Lesson
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Blade::directive('widget', function ($expression) {
$name = trim($expression, "'");
return "<?= resolve('App\Http\Widgets\\{$name}')->loadView(); ?>";
});
}
}
<?php
namespace App\Http\Widgets;
use App\Article;
class TrendingArticles extends Widget
{
public $title = 'Trending Articles';
public function articles()
{
return Article::take(3)->get();
}
}
<body>
@widget('TrendingArticles')
</body>
<?php
namespace App\Http\Widgets;
use ReflectionClass;
use ReflectionMethod;
use ReflectionProperty;
use Illuminate\Support\Str;
abstract class Widget
{
/**
* Load the view with the necessary data.
*
* @return \Illuminate\View\View
*/
public function loadView()
{
return $this->view()->with($this->buildViewData());
}
/**
* Load the view for the widget.
*
* @return \Illuminate\View\View
*/
public function view()
{
$name = Str::kebab(class_basename($this));
return view("widgets.{$name}");
}
/**
* Build the view data.
*
* @return array
* @throws \ReflectionException
*/
protected function buildViewData()
{
$viewData = [];
foreach ((new ReflectionClass($this))->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
$viewData[$property->getName()] = $property->getValue($this);
}
foreach ((new ReflectionClass($this))->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
if (! in_array($name = $method->getName(), ['loadView', 'view'])) {
$viewData[$name] = $this->$name();
}
}
return $viewData;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.