Skip to content

Instantly share code, notes, and snippets.

@lagbox
Last active August 5, 2018 18:46
Show Gist options
  • Save lagbox/919e8383a151f6315a695c723eae2c46 to your computer and use it in GitHub Desktop.
Save lagbox/919e8383a151f6315a695c723eae2c46 to your computer and use it in GitHub Desktop.
view factory share later
<?php
// View/Factory.php
...
public function shareLater($key, callable $value)
{
$keys = is_array($key) ? $key : [$key => $value];
foreach ($keys as $key => $value) {
$this->share($key, new Shareable($this->container, $value));
}
}
<?php
public function boot()
{
View::shareLater('currentUser', function () {
return auth()->user();
});
}
<?php
namespace Illuminate\View;
class Shareable
{
protected $container;
protected $shared;
public function __construct($container, $shared)
{
$this->container = $container;
$this->shared = $shared;
}
public function resolve()
{
if (is_callable($this->shared)) {
return $this->container->call($this->shared);
}
return $this->shared;
}
}
<?php
// View/View.php
protected function gatherData()
{
$data = array_merge($this->factory->getShared(), $this->data);
foreach ($data as $key => $value) {
if ($value instanceof Renderable) {
$data[$key] = $value->render();
} elseif ($value instanceof Shareable) {
$data[$key] = $value->resolve();
}
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment