Skip to content

Instantly share code, notes, and snippets.

@VanArmenia
Forked from JeffreyWay/AppServiceProvider.php
Created October 28, 2020 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VanArmenia/6351c654cfeb076b20519bfd2d9cac74 to your computer and use it in GitHub Desktop.
Save VanArmenia/6351c654cfeb076b20519bfd2d9cac74 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