2015-02-04 33 views
0

如何在控制器外部使用laravel雄辯模型?我似乎無法找出我應該使用的語句use "*insert class here*"。我有一個助手類,經常會使用我的「類別模型」。如何在助手類中使用laravel雄辯模型

這是我使用的代碼。當我使用類別:

<?php 

namespace Msh\Redirects; 

use Illuminate\Support\Facades\Config as Config; 
use Illuminate\Support\Facades\Input as Input; 


/** 
* This is the actual "product class" that generates the 301 redirect url's 
* 
* This is the product 
* 
* @author bgarrison 
*/ 
class StorefrontRedirectsGenerator implements RedirectsGenerator { 

    public function generateUrls() { 
     // Set the database to the name of the domain 
     Config::set('database.connections.mysql_tenant.database', Input::get('domain')); 

     // Grab all the categories 
     $categories = Category::all(); 

     // Use category information to determine request url's and target url's 
     $urlMapping = []; 
     $count = 0; 
     $categoryCount = 0; 
     foreach ($categories as $category) { 
      if ($category->Published == 1) { 
       $oldUrl = 'c-' . $category->CategoryID . '-' . $category->SEName . '.aspx'; 
       $urlMapping['category_urls'][$oldUrl][] = $category->SEName . '.html'; 
       $count++; 
       $categoryCount++; 
      } 
      if ($category->ParentCategoryID !== '0') { 
       $parentCategory = Category::where('CategoryID', '=', (int) $category->ParentCategoryID)->get(); 
       foreach ($parentCategory as $pcategory) { 
        $url = $pcategory->SEName . '/' . $urlMapping['category_urls'][$oldUrl][0]; 
        if (!in_array($url, $urlMapping['category_urls'][$oldUrl])) { 
         $urlMapping['category_urls'][$oldUrl][] = $url; 
         $count++; 
         $categoryCount++; 
        } 
       } 
      } 
     } 
     $urlMapping['category_urls']['count'] = $categoryCount; 
     return Response::json([ 
       'success' => true, 
       'count' => $count, 
       'data' => $urlMapping 
     ]); 
    } 

} 

回答

2

如果您的模型不在名稱空間內(使用Laravel 4的默認設置)。如果它是一個命名空間內

use Category; 

:添加此

use Your\Namespace\Category; 

當然,你總是可以直接指定完全合格的類名。這意味着,如果你的類沒有命名空間(在全局命名空間中存在的話)你用一個反斜槓,以確保你引用它絕對的,而不是相對於當前命名空間:

$categories = \Category::all(); 

而且如果類恰好是在命名空間,只需指定完整路徑:

$categories = Your\Namespace\Category::all(); 
+0

這做到了!萬分感謝。我仍然習慣了這些年後的命名空間:) –

+0

不客氣:) – lukasgeiter

+0

我會將它標記爲答案asap –

0

你應該沒問題。你要麼聲明它是這樣的:

use Category; 

use Namespace\If\Any\Category; 

前助手類,剩下的爲是。

或者使用這種方式:

$categories = \Category::all(); 

$categories = Namespace\If\Any\Category::all(); 
+0

我希望我可以將這兩個標記作爲答案,但作爲盧卡斯首先回答我將標記爲答案。 –