Skip to content

Instantly share code, notes, and snippets.

@troymcginnis
Last active April 29, 2018 20:29
Show Gist options
  • Save troymcginnis/8900fe76df52e856487def0f75e1c010 to your computer and use it in GitHub Desktop.
Save troymcginnis/8900fe76df52e856487def0f75e1c010 to your computer and use it in GitHub Desktop.
Sage 9 Component Controllers
<?php
// app/controllers/App.php
namespace App;
use Sober\Controller\Controller;
class App extends Controller
{
use Blocks;
//...
}
<?php
// app/controllers/partials/Blocks.php
namespace App;
trait Blocks
{
public static $blocks;
public function __construct()
{
self::$blocks = get_field('blocks');
}
public function blocks()
{
return self::$blocks;
}
public static function getBlockData()
{
if (sizeof(self::$blocks) === 0) {
return;
}
$defaults = [];
$data = self::$blocks[get_row_index() - 1];
if (!empty($defaults[get_row_layout()])) {
$data = array_merge($defaults[get_row_layout()], $data);
}
$data = self::setupBlockController($data);
return $data;
}
private static function setupBlockController($data)
{
$layout = $data['acf_fc_layout'];
$block = str_replace('_', '', ucwords($layout, '_'));
$blocks_path = dirname(get_template_directory()) . "/app/contollers/blocks/";
$controller_path = "{$blocks_path}/{$block}.php";
$class = __NAMESPACE__ . '\\' . $block;
if (file_exists($controller_path)) {
require_once $controller_path;
}
if (class_exists($class)) {
$controller = new $class();
$controller->__setup();
// Class alais
if (!class_exists($block)) {
class_alias($class, $block);
}
// Merge all the data together
$data = array_merge($data, $controller->__getData());
}
return $data;
}
}
{{-- resources/views/partials/content-page.blade.php --}}
<article>
@if (have_rows('blocks'))
@while (have_rows('blocks'))
@php(the_row())
@include('blocks.' . get_row_layout(), App::getBlockData())
@endwhile
@endif
</article>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment