Maz
Maz

It's me again!

I would like to talk with those who want about the component lifecycle in OctoberCMS, to really understand it.

All began when I ran into the exact same issue related here, I just wanted to check if some conditions were filled and if not, redirect the user.

You can easily reproduce it with a really basic component and page:

url = "/mycomponent"
layout = "default"
[myComponent]
==
{% component 'myComponent' %}

And a component which include a redirect directly on init() (which will not be the case, it's just for debug):

<?php namespace RomainMazB\RealEstate\Components;

use Illuminate\Support\Facades\Redirect;

class MyComponent extends \Cms\Classes\ComponentBase
{
    public function init()
    {
        return Redirect::to('/'); // This redirect won't happen
    }

    public function componentDetails()
    {
        return [
            'name' => 'MyComponent',
            'description' => 'Dummy component',
        ];
    }
}

And in plugin.php:

<?php namespace RomainMazB\RealEstate;

use System\Classes\PluginBase;

class Plugin extends PluginBase
{
    public function registerComponents()
    {
        return [
            'RomainMazB\RealEstate\Components\MyComponent' => 'myComponent',
        ];
    }
}

After some search, you will find the layout life cycle, and see the page component's onRun method is called at the 7th step but no mention about the component's init method but you may think it should be somewhere between step 2 and step 3 (relatively page onInit and layout onStart to save you a CTRL+TAB).

But it's not! After some tests (basically using dd into layout/page onInit and component's init), I discovered that init() method is called before the step 1! After having this issue, and discovered this, I'm feeling like "woot? when is it called? and why can't we redirect from it?" So I've searched and found that the page's included component's init method is called there, in the initComponents method, and I followed this "route" until I land in the CMS Controller run method.

But... I still don't have the answer to my question: why can't we redirect from component's init method? If you basically have a component's partial like:

Hello from the component

it will be displayed! Why?

Of course to solve the problem you can just add the redirect logic into the component onRun method but I'm a curious guy :)

[EDIT] Just discovered that we can redirect from init throwing a HTTPResponseException.

throw new HttpResponseException(redirect('404'));

Last updated

mjauvin
mjauvin

I don't have the answer, but the component's init() method is different that the page or layout onInit() methods which are called before each AJAX requests (before the AJAX handler is called).

mjauvin
mjauvin

Also of interest, the page life-cycle is not executed when a component AJAX handler runs...

1-3 of 3