如何在控制器内部获取由视图编辑器传递到某些视图的数据?



My View Composer 将一些数据传递给某些视图(当然,它可以工作(:

use IlluminateViewView;
use AppUtilHelper
class PublicSettingsComposer
{
public function compose(View $view)
{
$view->with('settings', Helper::readSettingsFromFile()); // json
}
}

相应的提供程序将添加到配置中,并为所有特定视图正确提供此编辑器:

view()->compose('public.layouts.*', 'AppHttpViewComposersPublicSettingsComposer');

但是,在我的一个视图中(仅(我需要来自数据库的特定信息,但因此我必须使用我的视图编辑器传递的一些数据:

class BranchController extends Controller
{
public function branches()
{
$settings = retrieve_settings_passed_by_PublicSettingsComposer; // This is what I need
$headquartersId = $settings->headquartersid;
return view('public.layouts.branches', [
'headquarters' => Branch::find($headquartersId) // Branch is a Model
]);
}
}

仅供参考:我使用的Laravel版本是:5.5


附言@moderators:请小心考虑我的问题重复。我知道有很多关于视图编辑器和将数据传递给视图以及从控制器中获取数据的问题。但是,我真的找不到有关此上下文的任何问题(标题通常具有误导性(。

我看到两个相当简单的解决方案。第一种方法是在每个请求中缓存解析的文件。另一种是为此作业使用实际缓存。

第一个选项非常容易实现。在Helper类中,您必须引入一个静态属性来保存读取文件的解析内容。然后,就像在单例模式中所做的那样,要么返回缓存的数据,要么先解析文件,缓存数据,然后返回。此方案解决了在应用的两个位置使用时每个请求分析设置两次的实际问题。

class Helper
{
protected static $cachedSettings;
public function readSettingsFromFile()
{
if (!self::$cachedSettings) {
self::$cachedSettings = // Do the parsing here. This should be your current implementation of Helper::readSettingsFromFile(). You can also put this in its own function.
}
return self::$cachedSettings;
}
}

另一种选择是使用实际缓存(外部缓存(。您可以将解析的文件缓存特定的次数(例如 1、3、5 或 10 分钟甚至更长时间(。或者,您可以永久缓存它,并在更新设置时使缓存失效(如果这种情况发生在您的应用中并且您知道它已更新(。

但是,仅当您的设置更改太频繁时,此解决方案才有意义。这也取决于您期望对应用的请求量。如果你的设置更改频率不太高(少于每 x分钟一次(,并且你的应用经常使用(每x 分钟更改多个请求(,那么它可能是一个可行的解决方案。

class Helper
{
public function readSettingsFromFile()
{
return Cache::remember(function () {
$settings = // Put your current calculation here
return $settings;
}, 3 * 60); // 3 * 60 = 180 seconds
}
}

最新更新