0

在 Laravel 4 中,如何创建模型实例并使其全局可用?即使在视图中。我正在寻找类似于使用 Auth::User->name 获取用户实例的方式(我的意思是语法,不存储在会话中)但在这种情况下它将是 ModelName::DefaultEntity->attribute .

再详细一点...

我正在编写一个可以容纳多个网站的应用程序——有点像 CMS。所以我有一个网站模型。每个网站模型都有一个 URL 属性,因此当用户访问 URL 时,应用程序可以从数据库中检索网站模型并适当地标记网站,例如标题、徽标、主题等...

我希望当前的网站模型在任何地方都可用,而不必在每个控制器/方法中创建一个新的网站实例。因此,在我的布局和视图中,我可以这样说:

{{ Website::Website()->name }}

或者

{{ CurrentWebsite::name }}

我通过在网站模型中创建静态方法实现了第一个:

public static function current()
{
    return Website::find(1); // just to test it for now
} 

但是这样一来,每次我说时它都必须进行数据库查询:

{{ Website::current()->name }}

再加上感觉不太对劲。

任何人都可以帮忙吗?

亲切的问候,

罗宾

4

3 回答 3

2

您可能正在寻找“共享容器绑定”。请参阅此处的文档

<?php
App::singleton('foo', function()
{
    return Website::whereCode('whoop')->first();
});

App::make('foo'); // every where you need it
于 2013-11-14T11:09:48.637 回答
1
  1. 创建普通班级。像 CurrentWebsite 或网站或其他任何东西。

    class Website {
        public function a() {
          //your code
        }
     }
    
  2. 创建外观 (WebsiteFacade.php)

    use Illuminate\Support\Facades\Facade;
    
    class WebsiteFacade extends Facade {
    
        protected static function getFacadeAccessor() { return 'website'; }
    
    }
    
  3. 创建服务提供者

        use Illuminate\Support\ServiceProvider;
    
        class WebsiteServiceProvider extends ServiceProvider {
    
        public function register()
        {
             $this->app->bind('website', function()
             {
                  return new Website();
              });
        }
        } 
    

4.转到您的 config/app.php 并添加以下内容:

 'providers' => array(
      'WebsiteServiceProvider'
 )

 'aliases' => array(
      'WebsiteFacade'
 )

5.Refrech自动装载机。现在您可以像这样在任何地方访问网站类:

    Website::a();
于 2013-11-14T15:11:56.880 回答
0

您已经拥有的很好,但是如果您只想阻止每次执行该查询,您可以缓存它:

public static function current()
{
    return Website::remember(10)->find(1); // just to test it for now
}

在你的 routes.php 中添加一个监听器:

 DB::listen(function($sql, $bindings, $time) { var_dump($sql); var_dump($bindings); });

并执行它:

{{ Website::current()->name }}

将在第一次执行时显示查询,但不会在第二次执行中显示,因为它已缓存。

于 2013-11-14T15:34:23.590 回答