Fork me on GitHub

Model

Basics

Model class in Hathoora PHP Framework is nothing more than the extension of container and provides an easy way to get database connection using getDBConnection() function.

Model class gives you the freedom to implement your business logic in anyway you want.

A sample model class is shown below in which we are extending hathoora\model\model class.

        
            namespace appNAME\controller
            {
                use hathoora\model\model

                class businessLogic extends model
                {
                    public function getSomething()
                    {
                        $db = $this->getDBConnection();

                        return $db->fetchArray('...');
                    }

                    // or use statically
                    public static function getSomethingElse()
                    {
                        $db = parent::getDBConnection();

                        return $db->fetchArray('...');
                    }
                }
            }
        
    

For further reading, checkout database and grid.

Model SAR

Hathoora PHP Framework also ships with a simple Active Records implementation. In order to use it simply extend hathoora\model\modelSAR and define the following:

  • public $_tableName property
  • public $_primaryKey property
  • public $_fields array of fields
  • public $_fields array of fields

You can also define the following optional functions:

  • customDBConnection(): to return a db connection (hathoora\database\db) to be used. This is useful if you are doing sharding.
  • postSave(): a function that is called when you save an object. This is useful of adding events for listeners to do something.

Lets walk through a few examples using the following note class.

        
            namespace appNAME\model
            {
                use hathoora\model\modelSAR

                class note extends modelSAR
                {
                    ####################################################
                    ##
                    ##      modelSAR Supported
                    ##
                    public $_tableName = 'note';
                    public $_primaryKey = 'note_id';
                    public $_fields = array(
                            'note_id',
                            'user_id',
                            'title',
                            'content',
                            'status',
                            'date_added',
                            'date_modified');

                    /**
                     * Sharding stuff
                     */
                    public static function customDBConnection($user_id = null)
                    {
                        // allows us to call this function manually
                        if (is_null($user_id))
                            $user_id = $this->user_id;

                        if ($user_id  % 2 == 0)
                            return parent::getDBConnection('eventConnection');
                        else
                            return parent::getDBConnection('oddConnection');
                    }

                    /**
                     * Notify event listeners
                     */
                    public function postSave()
                    {
                        if ($this->getSaveType() == 'add')
                            $this->getObserver()->addEvent('note.add', $this);
                        else if ($this->getSaveType() == 'update')
                            $this->getObserver()->addEvent('note.update', $this);
                        else if ($this->getSaveType() == 'delete')
                            $this->getObserver()->addEvent('note.delete', $this);
                    }



                    ####################################################
                    ##
                    ##      Custom Stuff
                    ##
                    /**
                     * Validation (custom function)
                     */
                    public function validation()
                    {
                        $arrValidations = array(
                            'user_id' => array(
                                'required' => true,
                            ),
                            'title' => array(
                                'required' => true,
                                'rules' => array(
                                    array(
                                        'minlength' => 3,
                                        'maxlength' => 150,
                                        'message' => 'Please enter a valid title.',
                                    ),
                                )
                            ),
                            'content' => array(
                                'required' => true,
                                'rules' => array(
                                    array(
                                        'callback' => array($this, 'validateRuleContent'),
                                    ),
                                )
                            )
                        );

                        return validation::validate($arrValidations, $this);
                    }

                    /**
                     * Content validation rule
                     */
                    public function validateRuleContent()
                    {
                        $noError = true;

                        if (businessRuleFailed)
                            $noError = 'Please try again after resolving the issue.';

                        return $noError;
                    }
                }
            }
        
    

New Record: For storing a new record, you can do something like the following:

        
            $note = new \appNAME\model\note();
            $note->user_id = 1;
            $note->title = 'Some title';
            $note->content = 'This is the content.';

            // or you can also do
            $note  = new \appNAME\model\note(array(
                'user_id' => 1,
                'title' => 'Some title',
                'content' => 'This is the content.'
            ));

            $arrError = note->validate();

            if (!is_array($arrError))
                $note_id = $note->save();
            else
                print_r($arrError);
        
    

Fetch Record: For fetching record, you can do something like the following:

        
            $note = \appNAME\model\note::fetch(array(
                                                    'whereRow' => array('note_id' => 1)));

            // manually figure out which shared to use
            $dbToUse = \appNAME\model\note::customDBConnection(1);
            $note = \appNAME\model\note::fetch(array(
                                                    'dsn' => &$dbToUse,
                                                    'whereRow' => array('note_id' => 1)));

            echo $post->content;
        
    

In this example we are building query using components of grid.


Delete Record: For deleting a record, you can do something like the following:

        
            $note = \appNAME\model\note::delete(array(
                                                    'whereRow' => array('note_id' => 1)));

            // manually figure out which shared to use
            $dbToUse = \appNAME\model\note::customDBConnection(1);
            $note = \appNAME\model\note::delete(array(
                                                    'dsn' => &$dbToUse,
                                                    'whereRow' => array('note_id' => 1)));

            // or if you already have a note object, then do
            $note->delete();
        
    

Accessing Container

By extending hathoora/model/* you have access to container.

Page Took:         5.82 msec
Page Memory:   528.02k
docs / viewController / view (200)
Request UUID: 59963af46d79c5.94198984
Get
Post
Cookies
Files
Session
Server
Response
No data.
No data.
No data.
No data.
No data.
REDIRECT_HATHOORA_ENV
prod
REDIRECT_STATUS
200
HATHOORA_ENV
prod
HTTP_HOST
hathoora.org
HTTP_X_FORWARDED_FOR
54.224.184.251
HTTP_X_REAL_IP
54.224.184.251
HTTP_CONNECTION
close
HTTP_ACCEPT_ENCODING
x-gzip, gzip, deflate
HTTP_USER_AGENT
CCBot/2.0 (http://commoncrawl.org/faq/)
HTTP_ACCEPT
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_IF_MODIFIED_SINCE
Sun, 23 Jul 2017 18:29:00 GMT
PATH
/sbin:/usr/sbin:/bin:/usr/bin
SERVER_SIGNATURE
Apache/2.2.15 (CentOS) Server at hathoora.org Port 80
SERVER_SOFTWARE
Apache/2.2.15 (CentOS)
SERVER_NAME
hathoora.org
SERVER_ADDR
192.168.1.11
SERVER_PORT
80
REMOTE_ADDR
207.126.164.119
DOCUMENT_ROOT
/var/websites/hathoora.org/docroot
SERVER_ADMIN
webmaster@hathoora.org
SCRIPT_FILENAME
/var/websites/hathoora.org/docroot/index.php
REMOTE_PORT
44176
REDIRECT_URL
/docs/v1/model
GATEWAY_INTERFACE
CGI/1.1
SERVER_PROTOCOL
HTTP/1.0
REQUEST_METHOD
GET
QUERY_STRING
REQUEST_URI
/docs/v1/model
SCRIPT_NAME
/index.php
PHP_SELF
/index.php
REQUEST_TIME_FLOAT
1503017716.447
REQUEST_TIME
1503017716
Status: 200
Headers:
Content-Type
text/html; charset=UTF-8
Configutation
Key Value
app.admin
Array
(
    [pattern] => /admin(|/)
    [directory] => hathoora
    [namespace] => hathoora\admin
)
app.docs
Array
(
    [pattern] => /docs(|/)
    [directory] => hathoora
    [dispatcher] => Array
        (
            [class] => customDispatcher
            [method] => dispatch
        )

)
app.site
Array
(
    [default] => 1
)
hathoora.logger
Array
(
    [profiling] => Array
        (
            [enabled] => 1
        )

    [logging] => Array
        (
            [enabled] => 1
            [level] => DEBUG
        )

    [webprofiler] => Array
        (
            [enabled] => 1
            [system] => 
            [show_redirects] => 
        )

)
hathoora.template
Array
(
    [engine] => Array
        (
            [name] => Stuob
        )

)
hathoora.database
Array
(
    [default] => mysql://dbuser:dbpassword@dbhost:3306/dbname
)
services.container
Array
(
    [class] => \hathoora\container
    [method] => getContainer
)
Logging (14)
hathoora.logger.logging.enabled: 1
# Time (msec) Level Memory (KB) Message
1 2.189 DEBUG 309.66 Configuration loaded:
Array
(
    [0] => app_prod.yml
    [1] => config_prod.yml
)
2 2.419 DEBUG 323.27 Listener "kernel.terminate[webprofiler]" has been added because of hathoora.logger.webprofiler.enabled
3 2.567 DEBUG 326.66 Event kernel.ready has been registered.
4 2.754 DEBUG 335.02 Calling App dispatcher (Array ( [class] => customDispatcher [method] => dispatch ) )...
5 2.896 DEBUG 349.45 Event kernel.route has been registered.
6 3.165 DEBUG 378.80 Event kernel.controller has been registered.
7 3.217 DEBUG 379.74 Calling controller (\docs\controller\viewController::view) with following params
Array
(
    [0] => v1
    [1] => model
)
8 3.808 INFO 467.07 Template (docs/v1/model.tpl.php) loaded
9 4.016 INFO 489.11 Template (/var/websites/hathoora.org/app/hathoora/docs//resources/templates/components/htmlMeta.tpl.php) loaded
10 4.147 INFO 490.36 Template (/var/websites/hathoora.org/app/hathoora/docs//resources/templates/components/flashMessages.tpl.php) loaded
11 5.474 INFO 442.63 Template (docs.tpl.php) fetched.
12 5.535 DEBUG 442.22 Event kernel.response has been registered.
13 5.575 DEBUG 443.41 Event kernel.terminate has been registered.
14 5.662 DEBUG 446.63 Event kernel.terminate->webprofiler has been notified.
Profiling
template
# Time (msec) Name Cached Took (msec)
1 3.322 docs.tpl.php 0 2.050