[TYPO3-mvc] Re: Inject your controller with vars from typoscript and/or db data

Nils Blattner nb at cabag.ch
Fri Feb 19 15:12:19 CET 2010


When I started out I had no idea whether I would store my project 
specific data in typoscript or in the db under a project row.
I finally decided to do a mix.

But when I was developing the application, I just ignored that aspect 
and put protected variables in my controllers holding the default data:


	
	/**
	 * @var int Pid of the login page to redirect to.
	 */
	public $loginPagePid = 1;

Yeah, yeah, maybe not perfect naming, but whatever!

So when I finally got around to include typoscript, I decided to use 
those properties instead of changing them all to the $this->settings[...].
This is extremely useful when you might have to switch getting data from 
the db instead of ts etc.
Makes the code a lot more manageable in my opinion than to go and change 
from $this->settings['...'] to some method and back.


	protected function initializeFromSettings() {
		// initialize certain variables from typoscript (ts, ...) or the 
project dataset (project, ...)
		// IMPORTANT: projectUid must be before any project, ...
		
		$vars = array(
			'projectUid' => 'ts,int',
			'defaultGroupPicture' => 'ts,string',
			...
			'firstDayOfTheWeek' => 'project,int',
			...
		);
		
		foreach ($vars as $key => $type) {
			// checks
			list($origin, $type) = explode(',', $type);
			$isset = false;
			$value = '';
			$key = trim($key);
			$origin = trim($origin);
			if ($origin == 'ts') {
				// get the value from typoscript
				$isset = isset($this->settings[$key]);
				$value = $this->settings[$key];
			} else if ($origin == 'project') {
				// get the value from the project record
				// if key is, say abcd, this will check if theres a method getAbcd() 
and execute it
				$method = 'get' . strtoupper(substr($key, 0, 1)) . substr($key, 1);
				$isset = method_exists($this->projectVariables, $method);
				if ($isset) {
					$value = $this->projectVariables->$method();
				}
			}
			
			// define types here, nonexisting types are ignored!
			if ($isset) {
				switch ($type) {
					case 'string' :
						$this->$key = $value;
						break;
					case 'int' :
						$this->$key = intval($value);
						break;
					case 'boolean':
						$this->$key = intval($value) == 1;
						break;
				}
			}
			
			// make sure the project is loaded! otherwise the 'origin' project 
will not work!
			if ($key == 'projectUid') {
				$this->projectVariables = 
$this->projectRepository->findByUid(intval($this->projectUid));
			}
		}
	}


More information about the TYPO3-project-typo3v4mvc mailing list