Jump to content

custom page class: How to use __construct() or similar


jom
 Share

Recommended Posts

Hi

I've started working with custom page classes. The basic example from Ryan's blog post works fine. Now: I'd like to set some object variables, which I can use in my methods. Usually this is done within the __constructor() method. My simplified example:

<?php namespace ProcessWire;

class ProgrammlistePage extends Page {
    public $header = '';
        
    public function __construct(){
        $this->header = 'some text';
        // parent::__construct();
    }

   public function header() {
        return $this->header;
    }
}

This results in an error in my nav function, related to Page.php (Trying to get property 'slashUrls' of non-object in /home/.../wire/core/Page.php on line 3245).

What am I doing wrong? I believe I should call the parent::__constructor(), but it didn't work either. I would appreciate a hint, where to look in the docs, because I feel I miss some basic understanding of the underlying mechanisms.

Thanks in advance!

Link to comment
Share on other sites

Page::__construct() takes a Template object as an argument:

/**
 * Create a new page in memory. 
 *
 * @param Template $tpl Template object this page should use. 
 *
 */
public function __construct(Template $tpl = null) {

	if(!is_null($tpl)) {
		$tpl->wire($this);
		$this->template = $tpl;
	} 
	$this->useFuel(false); // prevent fuel from being in local scope
	$this->parentPrevious = null;
	$this->templatePrevious = null;
	$this->statusPrevious = null;
}

So I think the constructor in your child class should be:

public function __construct(Template $tpl = null) {
	parent::__construct($tpl);
	$this->header = 'some text';
}

 

  • Like 4
Link to comment
Share on other sites

I have a follow up question: How can I get access to the active page from within the __constructor? Something like this:

public function __construct(Template $tpl = null) {
    parent::__construct($tpl);
    $this->header = page()->title; //does not work
}

I guess, I have to pass the active page to the constructor? But how/where?

In my page template file programmliste.php I refer to the custom class like this:

$content = page()->header();

Including the active page here is too late, as the the custom class has already been created, I guess?

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...