Jump to content

Ocs-server/Gfx4/Controllers

From KDE Community Wiki
Revision as of 21:31, 27 July 2015 by Snizzo (talk | contribs) (Created page with "Lastly, the more important of both the components, the Controller, represented by the EController class and located in the folder "controllers" following this filename syntax:...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Lastly, the more important of both the components, the Controller, represented by the EController class and located in the folder "controllers" following this filename syntax: <controllername>.controller.php

The controller is used to "glue" the data produced with the model and put it in the view in the correct order. In the controller will be written also all the logic of the application.

A Controller works closely with the Rewrite engine because the controller's name and methods responds to a particular section of the website. Every controller class name, in fact, should named after the "section" of the website that you want to handle. For example the MainController->index($args) above will be executed when www.mywebsite.com/main/index is called. This behaviour can be changed and adapted to some extent via the Rewrite engine. Check the correct wiki page for more info.

A controller's method can receive/check arguments that are mapped to the first argument of the method $args as an array, or can be accessed with the EController::arg_pos($p) and EController::arg_key($p) whether you need to access them by numeric key or by string key.

Small example of call to Controller class and arguments handling: URL: http://www.example.com/main/index/hello

<?php
class MainController extends EController
{
	public function index($args)
	{
		if($this->arg_key('hello')){
			echo 'yes'; //will print yes because 'hello' is a present parameter
		}

		if(isset($this->arg_pos(1)){
			echo $this->arg_pos(1); //this will print 'hello' as a string
		}
	}
}
?>

Here is a basic but complete example of a controller that fetches data from a model and sends it to a view:

main.controller.php

<?php
class MainController extends EController
{
	public function index($args)
	{
		EStructure::view("home");
	}
	
	public function last_news()
	{
		$articles = new ArticlesModel();
		EStructure::view("articles", $articles->getAll());
	}
}
?>

articles.model.php

<?php
class ArticlesModel extends EModel
{
	public function __construct()
	{
		parent::__construct("articles");
	}
	
	public function getAll()
	{
		$data = $this->find("*");
		return $data;
	}
}
?>

articles.views.php

<html>
	<head><title>Articles page</title></head>
	<body>
		<?php foreach($data as $article) { ?>
		<h1><?=$article['id']?></h1>
		<p><?=$article['text']?></p>
		<?php } ?>
	</body>
</html>