CakePHP2的 Sitemapの作り方
今更なんですが、CakePHP2的sitemapの作り方を。。。

Sitemapを作るなら、プラグインでさくっと作れるに決まっているわ!そうよ!うふふ
と思っていたら、返って柔軟に作りにくいことが分かり、Bakeryの基本的な手順にのっとって作ったほうが後々楽だったのでそのメモを。
なお、Bakeryは上記URLの手順はCakePHP1系ですが、基本的なことはほぼ一緒ですし、以下記載するコードは2.4で動作チェック済みです。
ではでは、CakePHP2的sitemap。
基本的にはControllerを作って、そのControllerに乗っ取ってview作ってルーティングでhttp://yourhost/sitemapにアクセス出来るようにするだけ。
SitemapsController.phpの作成
class SitemapsController extends AppController{
public $layout = 'xml/default';
public $uses = ['Post'];
public $helpers = ['Time'];
public $components = ['RequestHandler'];
function index (){
$this->set('posts', $this->Post->find('all', [ 'conditions' => ['is_published'=>1,'is_public'=>'1'] ]));
Configure::write ('debug', 0);
$this->RequestHandler->respondAs('xml');
}
}
エラーが万が一出力されないために、debugは0にしておきましょう。findするデータは任意でどんどん増やして行って下さい。
layoutファイルは、CakePHPにデフォルトでLayout/xml/default.ctpを使うことにしたので、layoutファイルの定義はxml/defaultになりました。
もちろん、layoutファイルは自分で作って設定しても大丈夫です。
RequestHandlerを使ってXMLとして表示させます。これが無いとxmlとして出力されず、だ〜っと文字列だけ出てします。
View/Sitemaps/index.ctpを作成
はい、後はもうお分かりですね、View/Sitemaps/index.ctpにfindしたデータを記載します。
<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc><?php echo Router::url('/',true); ?></loc>
<changefreq>daily</changefreq>
<priority>1.0</priority>
</url>
<!-- posts-->
<?php foreach ($posts as $post):?>
<url>
<loc><?php echo Router::url(array('controller'=>'posts','action'=>'view','id'=>$post['Post']['id']),true); ?></loc>
<lastmod><?php echo $this->time->toAtom($post['Post']['date_modified']); ?></lastmod>
<priority>0.8</priority>
</url>
<?php endforeach; ?>
</urlset>
app/Confit/routes.php ルーティングを記述
Router::connect('/sitemap', array('controller' => 'sitemaps', 'action' => 'index'));
これでhttp://yourhost/sitemapにアクセス出来ますね。
ほんと、プラグインに頼らず最初から自分で書いたら15分以内に出来たわ。