Router's Register function

Permalink
I saw some sample codes that had Route::Register but when I tried it, it didn't work. No register method on the class. I checked the API and found Router instead so I used it.

So when I tried this code:
Router::register('/redpoint/foo', 'Concrete\Package\MyPackageName\MyClassName::testMe', null, array());

I get this error when launching the site:
Call to a member function add() on null

I think it's this part in the Register function causing the error:
$this->collection->add($rtHandle, $route);

But I don't know what I should pass in $rtHandle though.

nathanprp
 
ramonleenders replied on at Permalink Best Answer Reply
ramonleenders
I did the following thing once (with some help). Make a single page controller and view like you normally do in your package. For example "product". In your package controller.php file (packages/your_package_hande/controller.php) we need some extra use statements:

use Route;
use Request;
use \Doctrine\Common\Annotations\AnnotationRegistry;


In your on_start function, add this code (or create the on_start function if it's not there yet):

AnnotationRegistry::registerLoader('class_exists');
$this->registerRoutes();


You will be calling registerRoutes, which we also need to create.

public function registerRoutes()
    {
        Route::register('/{slug}/p_{id}', function ($slug, $id) {
            global $cms;
            if (is_numeric($id)) {
                $r = Request::create('/product/view/' . $id . '/' . $slug);
                Request::setInstance($r);
                $response = $cms->dispatch($r);
                return $response->send();
            }
        }, 'product');
    }


As you can see, it's creating a request towards /product. This is your single page. It will use the "view" function within this single page, and passes 2 parameters named "id" and "slug". Within the product single page controller I had the view function like this:

public function view($id = null, $slug = null){
     // your code here
}


The route also got a name, called "product". So you have a way to generate a URL based on this route handle. If you need help with that, I can send you some additional code. If you want to do things a different way, I suppose one of the core members can help you with that.
nathanprp replied on at Permalink Reply
nathanprp
Thank you!

I had been pulled away from this task to focus on other tasks and just visited this now. It's working now.

I have a clarification though. My mistake was I was using this
use \Concrete\Core\Routing\Route;
thinking that's the same as
use Route;
. When I tried your code, it didn't work at first because of that. My question is why did that happened? I thought the Route controller under Core\Routing was what "use Route" was pointing to?
ramonleenders replied on at Permalink Reply
ramonleenders
Glad it worked out for you! :D