Skip to content

Instantly share code, notes, and snippets.

@lagbox
Last active September 7, 2020 09:31
Show Gist options
  • Save lagbox/0913f51f534ff9fe9941577ff5848eda to your computer and use it in GitHub Desktop.
Save lagbox/0913f51f534ff9fe9941577ff5848eda to your computer and use it in GitHub Desktop.
ShareLater functionality
<?php
//
public function boot()
{
View::shareLater('user', function () {
return auth()->user();
});
}
<?php
namespace Illuminate\Contracts\View;
interface Shareable
{
/**
* Resolve the shareable data.
*
* @return mixed
*/
public function share();
}
<?php
use Illuminate\View\ShareLater;
//
/**
* Share a callback to be resolved later.
*
* @param string $key
* @param callable|string $callback
* @param boolean $once
* @return void
*/
public function shareLater($key, $callback, $once = true)
{
$this->share($key, new ShareLater($this->container, $callback, $once));
}
<?php
namespace Illuminate\View;
use Illuminate\Contracts\View\Shareable;
class ShareLater implements Shareable
{
/**
* The IoC container instance.
*
* @var \Illuminate\Contracts\Container\Container
*/
protected $container;
/**
* The shared callback that will be resolved when the data is needed.
*
* @var callable|string
*/
protected $shared;
/**
* Whether the callback should be resolved only once.
*
* @var bool
*/
protected $once;
/**
* Has the callback been resolved.
*
* @var boolean
*/
protected $resolved = false;
/**
* The result of calling the callback.
*
* @var mixed
*/
protected $result;
/**
* Create a new ShareLater instance.
*
* @param \Illuminate\Contracts\Container\Container $container
* @param callable|string $shared
* @param bool $once
* @return void
*/
public function __construct($container, $shared, $once = true)
{
$this->container = $container;
$this->shared = $shared;
$this->once = $once;
}
/**
* Return the resolved shared data.
*
* @return mixed
*/
public function share()
{
if ($this->once && $this->resolved) {
return $this->result;
}
return tap($this->container->call($this->shared), function ($result) {
$this->result = $result;
$this->resolved = true;
});
}
}
<?php
use Illuminate\Contracts\View\Shareable;
//
public 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->share();
}
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment