1
+ <?php
2
+ // this controller shows an example of using models
3
+
4
+ // make sure you add the Controllers child name to the root namespace of your application
5
+ namespace RootNamespaceOfYourApp \Controllers ;
6
+
7
+ // import the base class of the controller
8
+ use PhpMvc \Controller ;
9
+ // import class for model annotation
10
+ use PhpMvc \Model ;
11
+
12
+ // expand your class with the base controller class
13
+ class AccountController extends Controller {
14
+
15
+ // create here action methods for the views of this controller
16
+ // the action methods must have a modifier public
17
+
18
+ public function __construct () {
19
+ // set model type for actions
20
+ Model::use (array ('index ' , 'login ' ), 'Login ' );
21
+
22
+ // required fields
23
+ Model::required ('Login ' , 'username ' );
24
+ Model::required ('Login ' , 'password ' );
25
+
26
+ // display name (for <label />) and text
27
+ Model::display ('Login ' , 'username ' , 'Username or Email ' , 'Enter any username. ' );
28
+ Model::display ('Login ' , 'password ' , 'Password ' , 'Enter 123. ' );
29
+
30
+ // custom validation
31
+ Model::validation ('Login ' , 'password ' , function ($ value , &$ errorMessage ) {
32
+ if ($ value != '123 ' ) {
33
+ $ errorMessage = 'Expected value is 123 ' ;
34
+ return false ;
35
+ }
36
+
37
+ return true ;
38
+ });
39
+ }
40
+
41
+ // default action
42
+ // url: /account or /account/index
43
+ public function index () {
44
+ if (isset ($ this ->getSession ()['user ' ])) {
45
+ // is user, redirect to home
46
+ return $ this ->redirectToAction ('index ' , 'home ' );
47
+ }
48
+
49
+ return $ this ->view ();
50
+ }
51
+
52
+ // login action, only for POST requests
53
+ // because the $model is required and object
54
+ // url: /account/login
55
+ public function login (\RootNamespaceOfYourApp \Models \Login $ model ) {
56
+ if (!$ this ->getModelState ()->isValid ()) {
57
+ // model is not valid, return login form
58
+ return $ this ->view ('index ' , $ model );
59
+ }
60
+
61
+ // model is valid, create session
62
+ $ session = $ this ->getSession ();
63
+
64
+ $ session ['user ' ] = $ model ->username ;
65
+
66
+ // redirect to home
67
+ return $ this ->redirectToAction ('index ' , 'home ' );
68
+ }
69
+
70
+ // logout action
71
+ // url: /account/logout
72
+ public function logout () {
73
+ $ this ->getSession ()->clear ();
74
+ return $ this ->redirectToAction ('index ' , 'home ' );
75
+ }
76
+
77
+ }
0 commit comments