Ad

Refactoring A Partial In October CMS

- 1 answer

Good day,

I have several partials that have code. In the code tab, I noticed that the code tab had similar looking code. Here are examples

Partial 1

function onStart()
{
    $x = MyModel1::where('myColumn', 'myValue')->first();
    // lots of stuff using $x functions
    $this['viewData'] = $x->getViewData();
}

Partial 2

function onStart()
{
    $x = MyModel2::where('myColumn', 'myValue')->first();
    // lots of stuff using $x functions
    $this['viewData'] = $x->getViewData();
}

MyModel1 and MyModel2 both implement the same interface, so they have the same functions.

My question is, where do I put the code that is similar? I can put it in a plugin but that doesn't feel correct. I can create a base class and have the partials call the parent method but won't that mean modifying the code in the vendor folder?

Ad

Answer

if you really need to manage your code you can create component and add that code there as they easily attached to other pages (down point is that you need to create a plugin)

you can write your code inside onRun method.

https://octobercms.com/docs/plugin/components#page-cycle

and instead directly assigning variables to this you need to assign them like

$this->page['var'] = 'value';

and now it will work same as you are doing.

Ad
source: stackoverflow.com
Ad