Controller Components

Strata believes in the “thin controller - fat models” theorem in that Controllers should not contain much code at all whereas Model should hold most of the application logic.

A method of inheriting behavior and simplifying Controller classes is to use PHP Traits.

You may then place all methods and concepts that do not relate to routed actions as part of multiple reusable traits.

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
<?php
namespace App\Controller;

use App\Controller\Component\ContactTrait;

class ContactController extends AppController
{
    use ContactTrait;

    public function before()
    {
        parent::before();

        $this->setupContactForm();
    }

    public function send()
    {
        if ($this->request->isPost()) {
            $this->attemptContactFormSave();
            return $this->redirect("ContactController", "index");
        }

        $this->notFound();
    }
}
?>

The ContactTrait can therefore be used by any Controller of your application which will gain the setupContactForm() and attemptContactFormSave() methods.

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
44
45
46
47
48
49
50
51
52
<?php
namespace App\Controller\Component;

use App\Model\ContactApplication;
use Exception;

/**
 * The contact trait allows a controller to automate the saving of a
 * contact-form type of object.
 */
trait ContactTrait
{
    /**
     * A model entity
     * @var App\Model\Entity\AppModelEntity
     */
    protected $contact;

    /**
     * Prepares the from object and assigns it to the current controller.
     */
    protected function setupContactForm()
    {
        $this->contact = ContactApplication::getEntity();
        $this->view->set("contactApplication", $this->contact);
    }

    /**
     * Attempts to save the object current set to the Controller's $contact attribute.
     * Prepares the variables for use in the views and sets GTM events.
     * @return bool State of success
     * @throws \Exception
     */
    protected function attemptContactFormSave()
    {
        if ($this->request->requestValidates($this->contact, $this->contact->getHoneypotName())) {
            try {
                $this->contact->assignRequest($this->request);

                $status = $this->contact->validates() && $this->contact->saveAll();
                $this->view->set("contactSuccess", $status);
                return $status;
            } catch (Exception $e) {
                $this->view->set("contactErrorMessage", $e->getMessage());
            }
        } else {
            $this->view->set("contactErrorMessage", "This request does not validate.");
        }
    }

}
?>