Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all "pages" in YII?

Tags:

php

sitemap

yii

I'm trying to create my own xml sitemap. Everything is done except for the part that I thought was going to be the easiest. How do you get a list of all the pages on the site? I have a bunch of views in a /site folder and a few others. Is there a way to explicitly request their URLs or perhaps via the controllers?

I do not want to make use of an extension

like image 889
coderama Avatar asked Jan 14 '13 09:01

coderama


2 Answers

You can use reflection to iterate through all methods of all your controllers:

Yii::import('application.controllers.*');
$urls = array();

$directory = Yii::getPathOfAlias('application.controllers');
$iterator = new DirectoryIterator($directory);
foreach ($iterator as $fileinfo)
{
    if ($fileinfo->isFile() and $fileinfo->getExtension() == 'php')
    {
        $className = substr($fileinfo->getFilename(), 0, -4); //strip extension
        $class = new ReflectionClass($className);

        foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method)
        {
            $methodName = $method->getName();
            //only take methods that begin with 'action', but skip actions() method
            if (strpos($methodName, 'action') === 0 and $methodName != 'actions')
            {   
                $controller = lcfirst(substr($className, 0, strrpos($className, 'Controller')));
                $action = lcfirst(substr($methodName, 6));
                $urls[] = Yii::app()->createAbsoluteUrl("$controller/$action");
            }
        }
    }
}
like image 83
Pavle Predic Avatar answered Oct 08 '22 09:10

Pavle Predic


You need to know what content you want to include in your sitemap.xml, I don't really think you want to include ALL pages in your sitemap.xml, or do you really want to include something like site.com/article/edit/1 ?

That said, you may only want the result from the view action in your controllers. truth is, you need to know what you want to indexed.

Do not think in terms of controllers/actions/views, but rather think of the resources in your system that you want indexed, be them articles, or pages, they are all in your database or stored somehow, so you can list them, and they have a URI that identifies them, getting the URI is a matter of invoking a couple functions.

like image 43
Asgaroth Avatar answered Oct 08 '22 08:10

Asgaroth