Skip to content

Instantly share code, notes, and snippets.

@JeffreyWay
Last active November 6, 2021 11:51
Show Gist options
  • Save JeffreyWay/9e92f1399a588a5533e87b449c812b93 to your computer and use it in GitHub Desktop.
Save JeffreyWay/9e92f1399a588a5533e87b449c812b93 to your computer and use it in GitHub Desktop.
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