如何在助手类中使用laravel-Eloquent模型


How to use laravel Eloquent model in helper class

如何在控制器之外使用laravel-Eloquent模型?我似乎找不到应该使用什么use "*insert class here*"语句。我有一个助手类,它将经常使用我的"类别模型"。

这是我正在使用的代码。当我使用类别:时,它失败了

<?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
        ]);
    }
}

如果您的模型不在命名空间内(Laravel 4的默认设置)。添加此:

use Category;

如果它在名称空间内:

use Your'Namespace'Category;

当然,您总是可以直接指定完全限定类名。这意味着,如果你的类没有命名空间(存在于全局命名空间中),你可以使用反斜杠来确保你引用它是绝对的,而不是相对于当前命名空间:

$categories = 'Category::all();

如果类恰好在命名空间中,只需指定完整路径:

$categories = Your'Namespace'Category::all();

你应该没事的。你要么这样声明:

use Category;

use Namespace'If'Any'Category;

在你的助手课之前,让其余的保持原样。

或者这样使用:

$categories = 'Category::all();

$categories = Namespace'If'Any'Category::all();