在Laravel项目中生成动态站点地图,而无需使用Composer


generate dynamic sitemaps in a laravel project without using composer

我想为我的 laravel 项目生成Dynamic sitemap。我已经在很多网站上搜索了答案。他们中的一些人使用作曲家来描述它。我不知道该怎么做。在其他一些站点中,他们编写代码以循环从数据库获取URL。在我的项目数据库中,我没有保存任何网址。我的项目是一个面向医生和患者的网站。那么有没有人知道如何写php / laravel codes for dynamic sitemap generation.?

编辑

我是 laravel 的新手,所以我只是不熟悉这位作曲家。 任何人都可以告诉我,如果我从 GitHub 下载 LaRavel-Sitemap-master.zip,我可以提取它并保存在我的项目目录中? 如果有人请回答这个问题,那将非常有帮助。

将此行添加到您的路线中.php

Route::get('/sitemap', function()
{
   return Response::view('sitemap')->header('Content-Type', 'application/xml');
});

创建新文件应用程序''Http''中间件''站点地图.php

<?php namespace App'Http'Middleware;
use Closure;
use Carbon'Carbon;
use Illuminate'Contracts'Auth'Guard;
class sitemap {
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  'Illuminate'Http'Request $request
     * @param  'Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ( !$request->is("sitemap") && $request->fullUrl() != '' && $this->auth->guest() )
        {
            $aSiteMap = 'Cache::get('sitemap', []);
            $changefreq = 'always';
            if ( !empty( $aSiteMap[$request->fullUrl()]['added'] ) ) {
                $aDateDiff = Carbon::createFromTimestamp( $aSiteMap[$request->fullUrl()]['added'] )->diff( Carbon::now() );
                if ( $aDateDiff->y > 0 ) {
                    $changefreq = 'yearly';
                } else if ( $aDateDiff->m > 0) {
                    $changefreq = 'monthly';
                } else if ( $aDateDiff->d > 6 ) {
                    $changefreq = 'weekly';
                } else if ( $aDateDiff->d > 0 && $aDateDiff->d < 7 ) {
                    $changefreq = 'daily';
                } else if ( $aDateDiff->h > 0 ) {
                    $changefreq = 'hourly';
                } else {
                    $changefreq = 'always';
                }
            }
            $aSiteMap[$request->fullUrl()] = [
                'added' => time(),
                'lastmod' => Carbon::now()->toIso8601String(),
                'priority' => 1 - substr_count($request->getPathInfo(), '/') / 10,
                'changefreq' => $changefreq
            ];
            'Cache::put('sitemap', $aSiteMap, 2880);
        }
        return $next($request);
    }
}

并创建新的视图文件资源''视图''站点地图.blade.php

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
        xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
    @foreach( Cache::get('sitemap') as $url => $params )
    <url>
        <loc>{{$url}}</loc>
        <lastmod>{{$params['lastmod']}}</lastmod>
        <changefreq>{{$params['changefreq']}}</changefreq>
        <priority>{{$params['priority']}}</priority>
    </url>
    @endforeach
</urlset>

在文件 app''Http''Kernel 中向受保护的$middleware数组添加一个条目.php

'sitemap' => 'App'Http'Middleware'sitemap'

假设您希望网站的sitemap.xml文件包含指向数据库中所有医生和患者的链接,您可以这样做:

在路由中.php文件..

Route::get("sitemap.xml", array(
    "as"   => "sitemap",
    "uses" => "HomeController@sitemap", // or any other controller you want to use
));

在 HomeController.php 文件中(如果您决定使用 HomeController)。

public function sitemap()
{
    $doctors = Doctor::remember(59) // chach this query for 59 minutes
        ->select(["id", "updated_at"]) 
        // you may want to add where clauses here according to your needs
        ->orderBy("id", "desc")
        ->take(50000) // each Sitemap file must have no more than 50,000 URLs and must be no larger than 10MB
        ->get();
    $patients = Patient::remember(59) // chach this query for 59 minutes
        ->select(["id", "updated_at"]) 
        // you may want to add where clauses here according to your needs
        ->orderBy("id", "desc")
        ->take(50000) // each Sitemap file must have no more than 50,000 URLs and must be no larger than 10MB
        ->get();
    $content = View::make('sitemap', ['doctors' => $doctors, 'patients' => $patients]);
    return Response::make($content)->header('Content-Type', 'text/xml;charset=utf-8');
}

在views/Sitemap.blade.php file..

<?php echo '<?xml version="1.0" encoding="UTF-8"?>' ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
@foreach($doctors as $doctor)
    <url>
        <loc>{{ URL::route("doctors.show", [$doctor->id]) }}</loc>
        <lastmod>{{ gmdate(DateTime::W3C, strtotime($doctor->updated_at)) }}</lastmod>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>
@endforeach
@foreach($patients as $patient)
    <url>
        <loc>{{ URL::route("patients.show", [$patient->id]) }}</loc>
        <lastmod>{{ gmdate(DateTime::W3C, strtotime($patient->updated_at)) }}</lastmod>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>
@endforeach
</urlset>

检查 https://github.com/RoumenDamianoff/laravel-sitemap

一个简单的站点地图生成器,适用于 Laravel 4。

Route::get('sitemap', function(){
    // create new sitemap object
    $sitemap = App::make("sitemap");
    // set cache (key (string), duration in minutes (Carbon|Datetime|int), turn on/off (boolean))
    // by default cache is disabled
    $sitemap->setCache('laravel.sitemap', 3600);
    // check if there is cached sitemap and build new only if is not
    if (!$sitemap->isCached())
    {
         // add item to the sitemap (url, date, priority, freq)
         $sitemap->add(URL::to('/'), '2012-08-25T20:10:00+02:00', '1.0', 'daily');
         $sitemap->add(URL::to('page'), '2012-08-26T12:30:00+02:00', '0.9', 'monthly');
         // get all posts from db
         $posts = DB::table('posts')->orderBy('created_at', 'desc')->get();
         // add every post to the sitemap
         foreach ($posts as $post)
         {
            $sitemap->add($post->slug, $post->modified, $post->priority, $post->freq);
         }
    }
    // show your sitemap (options: 'xml' (default), 'html', 'txt', 'ror-rss', 'ror-rdf')
    return $sitemap->render('xml');
});

我已经用过了。效果很好!

更新 #1

为了消除混淆,让我们举一个例子。

假设我有一个博客表,其中包含idtitleblog

我有路线,Route::get('blog/{blog}',['as' => 'blog.show', 'uses' => 'Blog@show'];

首先,我将获取内容,通过$blogs = DB::table('blog')->get();

$blogs将包含结果。

我只会循环,

foreach($blogs as $i)
{
     $sitemap->add(route('blog.show',[$i->title]), '2014-11-11', '1.0','daily');
}

我所有的博客都添加到站点地图中。