Skip to content

Using DataObjects as Pages

Damian Mooyman edited this page Jun 27, 2013 · 1 revision

You can use dataobjects as pages by adding the OpenGraphObjectExtension to your dataobject, in the same way that the module does by default for the Page type. In fact, this is what I've done for one of my projects.

Just make sure you implement AbsoluteLink and MetaTags in your dataobject and you can extend any of the opengraph interfaces.

Then in your page class, you simply delegate the responsibility for adding metatags to the object in question.

As the opengraph properties are elements of the respective data objects, the dataobject is the correct place to implement them, not in the controller.

Note that below I've used a custom opengraph object, but it would work just as well with one of the built in types.

class PhotoEntry extends DataObject implements IOGPhoto {

	function AbsoluteLink($action = 'show') {
		// Code to generate url to this dataobject
	}

	public function MetaTags($includeTitle = true) {
		$tags = "";

		// Insert non-OG metatags here as you normally would
                  
		$this->extend('MetaTags', $tags);
		return $tags;
	}

	// My custom OG object property
	public function getOGAuthor() {
		return $this->Author();
	}
}

interface IOGPhoto extends IOGObject {
	
	function getOGAuthor();
}



class EntryPage extends Page {

	function MetaTags($includeTitle = true) {
		
		if(	Controller::curr() instanceof EntryPage_Controller && 
			($record = Controller::curr()->getSelectedEntry())) {
			return $record->MetaTags($includeTitle);
		}
		
		return parent::MetaTags($includeTitle);
	}
}

The yaml code I use to hook up my custom OG object type is as below

PhotoEntry:
  extensions:
    - 'OpenGraphObjectExtension'
OpenGraph:
  types:
    'appnamespace:photo':
      interface: IOGPhoto
      tagbuilder: OGPhoto

and my tag builder

class OGPhoto extends OpenGraphBuilder {

    protected function appendPhotoTags(&$tags, IOGPhoto $photo)
    {
        $this->appendTag($tags, 'appnamespace:author', $photo->getOGAuthor());
    }

    public function BuildTags(&$tags, $object, $config)
    {
        parent::BuildTags($tags, $object, $config);

        $this->appendPhotoTags($tags, $object);
    }
}
Clone this wiki locally