Request and Response

This tutorial covers Artaengine Request and Response classes.

Request

While a Request object can be created manually, in an Artaengine application factory methods the first argument is always a Request instance. Assuming $request is an instance of class Request the below examples show the usages.

Get value:

/* check request method with the "is" methods */
if ($request->isPost()) {

}
/* get value of $_POST['name'] or Null if key not exists  */
$name = $request->Post->name;
// or
$name = $request->Post->get('name');
/* get value of $_POST['name'] or 'no-name' if key not exists */
$name = isset($_POST['name'])? $_POST['name']: 'no-name';
$name = $request->Post->get('name', 'no-name');
/* get value of $_POST['id'] if its numeric convert to integer
   otherwise return 0 */
$id = $request->Post->get('id', 0, T::INT);
/* get value of $_POST['users-email'] if its not a valid email
   format return Null */
$email = $request->Post->get('users-email', Null, T::EMAIL);

$_POST => array(
    'user'          => 'U',
    'user-name'     => 'Arta',
    'user-email'    => 'arta@arta.com',
    'bad-user'      => 'bad',
    'baduser-'      => 'B',
    'aaaa-user-bbb' => 'good',
);
/* get values where key starts with:  */
$data = $request->Post->with('user-');
$dataWouldBe => array(
    ''      => 'U',
    'name'  => 'Arta',
    'email' => 'arta@arta.com',
);
/* get values where key looks like:  */
$data = $request->Post->like('user-');
$dataWouldBe => array(
    'user'          => 'U',
    'user-name'     => 'Arta',
    'user-email'    => 'arta@arta.com',
    'baduser-'      => 'B',
    'aaaa-user-bbb' => 'good',
);
/* check value for a key */
if ($request->Post->hasValue('user', 'U')) {

}

/* upload files */
$rules = array(
    'size'   => '2M',
    'plugin' => 'PhotoEdit::isPhoto',
);
foreach ($request->Upload as $key => $uploadedFile) {
    if ($uploadedFile->validate($rules)) {
        $uploadedFile->moveTo('/path/to/file.png');
    }
}

Put/Set a value:

/* set/put a value to key: name in session */
$_SESSION['name'] = 'Arta';
$request->Session->name = 'Arta';
$request->Session->set('name', 'Arta');
/* set/put a value to key: name in cookie */
setcookie(
    'name',
    'Arta',
    time()+Arta::g('cookie_expire', 259200)*60,
    '/',
    False
);
$request->Cookie->name = 'Arta';
$request->Cookie->set('name', 'Arta');
/* put an array in cookie */
$request->Cookie->items = array('pet' => 'Rabbit', 'food' => 'Hay',);
$request->Cookie->set('items', array('pet' => 'Rabbit', 'food' => 'Hay',));
/* EXCEPTION: Cookie->set() can have more parameters: */
$request->Cookie->set(
    'name', // key
    'Arta', // value  
    60,     // expire
    '/',    // path
    False,  // domain
    False,  // secure
    False   // HTTP only
);
$request->Cookie->set('name', 'Arta', 60);    // expires in 60 seconds
$request->Cookie->set('name', 'Arta', '60I'); // expires in 60 minutes
$request->Cookie->set('name', 'Arta', '60H'); // expires in 60 hours
$request->Cookie->set('name', 'Arta', '60D'); // expires in 60 days
$request->Cookie->set('name', 'Arta', '60M'); // expires in 60 months

Check if a key exists:

if ($request->Get->has('user_data')) {
    echo 'exists';
}

if ($request->Get->has('user_data')) {
    echo 'exists';
}

Remove item(s):

/* remove all items */
$request->Session->clear();
/* remove one item */
$request->Session->remove('name');
/* remove more items */
$request->Session->remove('name', 'age', 'email');

Only for Session:

// set max life
$request->Session->expire(2); // minutes
// unset and destroy session
$request->Session->destroy();
// close session
// always close the session if you do not need to do more actions on
// the session but the script is not finished yet
$request->Session->close();
// get session id
$sessionId = $request->Session->id();
// regenerate session id
$request->Session->regenerate();

Request methods for other arrays:

$source = array('name' => 'Myname', 'age' => 7,);
$name = Request::input($source, 'name', 'default', T:STRING);
$name = Request::with($source, 'na');
$name = Request::like($source, 'na');

URLs:

// BASE_URL
echo BASE_URL; // http://my-app.com/
echo $request->baseUrl();
//current URL
echo $request->currentUrl(); // http://my-app.com/current
// current URL == BASE_URL
if ($request->isRoot()) {
    echo 'yes';
}
// create URL based on BASE_URL
echo $request->makeRelativeUrl('admin/clients/7');
// create URL based on current URL
echo $request->makeRelativeUrl('admin/clients/7', 'current');
/* get part(s) of URL, $part can be one of:
   'queryKeys', 'scheme', 'protocol', 'port', 'current', 'base',
   'server',  'physical', 'path', 'file' or 'full' */
echo $request->url($part)
// number of URL paths in current URL
echo $request->pathCount();
print_r($request->path()); // array of URL paths
echo $request->paths(); // string of URL paths
echo $request->path(2);    // second path
// number of query-string parameters:
echo $request->queryStringCount();
print_r($request->queryString('key1')); // array of query-string params
// join URL parts
$var = $request->joinUrl(array(
    'protocol' => 'http',
    'user'     => '',
    'pass'     => '',
    'host'     => 'artaengine.com',
    'port'     => '',
    'path'     => 'tutorials/request-response',
    'fragment' => 'request',
    'query'    => array(
        'key1' => 'val1',
        'key2' => 'val2',
        'key3' => 'val3',
    ),
));

To learn more see:

Response

Factories can simply be a functions or class methods. A factory class should(not mandatory) inherit from Response. In all the provided examples in this tutorial a factory class inherits from Response.

Obviously when you do not require any feature from Response your class does not need to inherit from it. However you can always manually create an instance of Response and use it, this is always the case with function factories because they do not have a class to inherit from Response.

Another obvious thing is that you may design a hierarchy structure for your factories where they inherit from each other (e.g. a parent which handles common things like menus) the top parent can inherit from Response so the derived factories are also inheriting from Response.

class Website extends Responseif {

    public $js = array(
        'jquery',
    );
    public $css = array(
        'portal',
    );

    public function contents($request, $menu='index') {
        // set page title
        $this->title('Website Title');
        // set template variables
        $this->menus = array(
            'index' => 'Home',
            'about' => 'About',
            'faq'   => 'Faq',
        );
        $this->selected = $menu;
        // show template
        $this->show('home/index.xhtml');
    }

    public function form($request) {
        // set variables to be seen by template or
        // JSON pack
        $this->data = array(
            'name'  => '',
            'age'   => '',
            'email' => '',
        );
        $this->formtitle = 'title';
        $this->formtype  = 'add';
        // get template contents
        $this->html = $this->getTemplate('forms/form.xhtml');
        // send all above data as JSON - response to an AJAX request
        $this->writeJson();
    }

    private function examples() {
        // set header(s)
        $this->headers('Content-type: application/pdf',
            'Content-Disposition: attachment; filename="downloaded.pdf');
        $this->headers(array(
            'Content-type: application/pdf',
            'Content-Disposition: attachment; filename="downloaded.pdf',
        ));
        // redirect to BASE_URL
        $this->redirect();
        // redirect to BASE_URL/tutorials/request-response
        $this->redirect('/tutorials/request-response');
        // redirect to google.com
        $this->redirect('http://www.google.com');
        // file contents, guess file type automatically
        $this->showFile('/images/image.png');
        // file contents
        $this->showFile('/images/image.png', 'image/png');
        // download file, guess file type automatically
        $this->sendFile('/files/tutorial.pdf');
        // download file as new-name.pdf, guess file type automatically
        $this->sendFile('/files/tutorial.pdf', 'new-name.pdf');
        // download file, download as new-name.pdf
        $this->sendFile('/files/tutorial.pdf', 'new-name.pdf',
            'application/pdf');
        // echo a string or array of strings, default charset is utf-8
        $this->write('text');
        $this->write('text', 'utf-8');
        $this->write(array('text1', 'text2',));
        // remove all template variables
        $this->clear();
        // get template object (instance of template engine)
        // assuming template object name is 'tpl'
        $obj = Template::get('tpl');
        // or
        $obj = $this->tpl;
    }
}

To learn more see:

Example

Request and Response
TOP