Hoe model koppelen aan controller?
Iemand tips?
Code (php)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Gewijzigd op 06/10/2014 22:43:09 door Roy B
Code (php)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php
// controller.php
class HomeController extends BaseController {
public function __construct() {
parent::__construct();
}
public function index() {
$model = $this->loadModel('MODELNAME', 'MODELPATH');
$model->function();
}
}
//BaseController.php
class BaseController {
function __construct() {
$this->openDatabaseConnection();
$this->twig = $this->loadTwig();
$this->blade = $this->loadBlade($view, $data = array() );
}
/**
* Load the model with the given name.
* loadModel("home/index", "HomeModel") would include models/home/index.model.php and create the object in the controller, like this:
* $model = $this->loadModel("home/index", "HomeModel");
* Note that the model class name is written in "CamelCase", the model's filename is the same in lowercase letters
* @param string $model_name The name of the model
* @return object model
*/
public function loadModel($model_path, $model_name) {
require APP . MOD . strtolower($model_path) . MOD_F;
// return new model (and pass the database connection to the model)
return new $model_name($this->db);
}
}
}
?>
// controller.php
class HomeController extends BaseController {
public function __construct() {
parent::__construct();
}
public function index() {
$model = $this->loadModel('MODELNAME', 'MODELPATH');
$model->function();
}
}
//BaseController.php
class BaseController {
function __construct() {
$this->openDatabaseConnection();
$this->twig = $this->loadTwig();
$this->blade = $this->loadBlade($view, $data = array() );
}
/**
* Load the model with the given name.
* loadModel("home/index", "HomeModel") would include models/home/index.model.php and create the object in the controller, like this:
* $model = $this->loadModel("home/index", "HomeModel");
* Note that the model class name is written in "CamelCase", the model's filename is the same in lowercase letters
* @param string $model_name The name of the model
* @return object model
*/
public function loadModel($model_path, $model_name) {
require APP . MOD . strtolower($model_path) . MOD_F;
// return new model (and pass the database connection to the model)
return new $model_name($this->db);
}
}
}
?>
Zo ongeveer doe ik het.
Let op in de praktijk kan het ook anders.
Wouter, doet je BaseController dan niet te veel? Je opent al in de constructor altijd een databaseverbinding (maar dat hoort bij het model) en je gaat vervolgens in de weer met Twig en Blade (maar dat zijn template engines voor de views). Het lijkt daardoor meer een front controller.