6. Access your web app in your favorite browser and enjoy this magnify Hello World!
#### Explanation
All routes are a mapping class with extends the primary Controller class. In a simple term, the class name in controller is *Controller****Folder****Filename*.
`class ControllerFolderFile extends Controller {
}`
The public function named `index()` is a default function to generate the page.
`public function index() { }`
Array `$this->data` receives in array format the variables to send to template, in this sample called **variable** with the string *Hello World!*.
In the last we finish with a simple `$this->out();` to indicate the output and process template file. It's an automated mechanism to link this controller with the respective viewer.
The viewer in this sample is a twig template format ([Twig page](https://twig.symfony.com)). ExacTI Phacil Framework permits to use various PHP template engines, like Twig, Mustache, Dwoo and Smarty.
## Config file Parameters
A simple description of default constants configurations in *config.php* file.
| Constant | Type | Description | Required |
| ----- | ----- | ----- | ----- |
| HTTP_URL | string | Contains the URL for this WEB APP | Yes |
| HTTPS_URL | string | Same this HTTP_URL, but in SSL format |
| HTTP_IMAGE | string | The image URL |
| CDN | string | CDN URL to use for static content |
| DB_CONFIG | boolean | Permit to use configurations direct in database. Requires database installation. Values: true or false. | Yes |
Phacil Framework count with three methods for output content: `$this->response->setOutput()`, `$this->render()` and `$this->out()`.
### setOutput
When you call a `$this->response->setOutput` inside a controller, you specify an output of content to screen without template. It's very useful for JSON, XML or others data contents.
##### Sample
```php
<?php
class ControllerDemoSample extends Controller {
public function index() {
$variable = 'value';
$this->response->setOutput($variable);
// prints "value" in screen
}
}
```
### render
The `$this->render` just render the controller with template but not output this.
Needs to specify a `$this->template` to associate with template file.
It's much used in children's controllers, like headers and footers.
##### Sample
```php
<?php
class ControllerCommonHeader extends Controller {
public function index() {
$variable = 'value';
$this->template = 'default\common\header.twig';
$this->render();
}
}
```
### out
The `$this->out` is a smart way to output content to screen and combine the render with an associative template. For sample, if you have a controller in a file called `sample.php` inside the `demo` controller folder and a viewer called `sample.twig` inside `demo` view folder, automatically links with one another and the `$this->template` isn't need (Unless you want to specify another template with a different name).
If you specify `$this->out(false)` the auto childrens "header" and "footer" are not loaded.
For functions inside the controller that are different from index, for automatic mapping with the template it is necessary to add an underscore (_) after the controller name and add the function name (E.g.: contact_work.twig to link with the route common/contact/work, see *Routes* section for more information).
##### Sample
```php
<?php
class ControllerCommonContact extends Controller {
public function index() {
$this->document->setTitle('Contact Us');
$this->out();
// automatically link with common/contact.twig template
}
public function work() {
$this->document->setTitle('Work with Us');
$this->out();
// automatically link with common/contact_work.twig template
}
}
```
## Template Engines Support
This framework supports this PHP templates engines:
- TPL (basic template with PHP and HTML);
- [Twig](https://twig.symfony.com);
- [Mustache](https://mustache.github.io);
- [Dwoo](http://dwoo.org);
- [Smarty](https://www.smarty.net).
To use a determined template engine, just create a file with name of engine in extension, for sample, if you like to use a Twig, the template file is **demo.twig**, if desire the Mustache template, use **demo.mustache** extension file.
The ExacTI Phacil Framework allows to use various template engines in the same project.
## Easy made functions
This framework is very focused in agile, security and reusable code in PHP. Contains a very utile functions we see in the next section.
### Database
To execute a query:
```php
$variable = $this->db->query("SELECT * FROM mundo");
```
Without SQL Cache (if enabled):
```php
$variable = $this->db->query("SELECT * FROM mundo", false);
```
Escape values to more security (no SQL injection issue):
`$this->db->escape($value)`
To get these rows:
`$variable->rows`;
Get one row: `$variable->row`;
Number of rows: `$variable->num_rows`;
Sample:
```php
<?php
class ModelDemoSample extends Model {
public $data = array();
public function dataSample ($code) {
$variable = $this->db->query("SELECT * FROM settings WHERE code = '". $this->db->escape($code). "'");
If you need an extra database connection or a different driver/database access, you can use the `$this->load->database($driver, $hostname, $username, $password, $database);` method (see more about databases functions in the Databases section of this document).
The name of database is a registered object to access database functions.
This load is simple and registry to object of origin.
$sql = $this->nameDatabase->query("SELECT * FROM mundo");
return $sql->rows;
}
}
```
## Models
This framework is totally MVC (Model, View and Controller) based. The models are just like the controllers and uses the same structure, with a different folder.
To create a model, put in the models folder a directory and file with the code.
```php
<?php
class ModelFolderFile extends Model {
public function SayMyName() {
return "Heisenberg";
}
}
```
To use this model in a controller, you can use the `loader`.
```php
<?php
class ControllerFolderFile extends Controller {
public function index() {
$this->load->model('folder/file');
echo $this->model_folder_file->SayMyName();
// this output is "Heisenberg".
}
}
```
## Constructs and Destructs
In some cases, we need to add a __construct or __destruct in a class to better code practices. To call a constructs in controllers and models, use the `$registry` parent:
```php
public function __construct($registry)
{
parent::__construct($registry);
// YOUR CODE HERE AFTER THIS LINE!
}
```
## Requests and Sessions
To use a magic request system, you just need to call a `$this->request` method. For sample, to obtain a POST value, use `$this->request->post['field']` to get the post value with security.
For a \$_SERVER predefined variables, use `$this->request->server['VALUE']` and $this->request->get() for \$_GET values.
The advantages to use this requests instead the predefined variables of PHP are more the more security, upgradable and unicode values.
### Sessions
Sessions is a little different method, you can define and use with `$this->session->data['name']`.
## Special controller parameters
| Parameter | Type | Description|
| ----- | ----- | ----- |
| `$this->template` | string | Specify manually the path to template |
| `$this->children` | array | Load in a template variable other renders of web app. Th children's *footer* and *header* is default loaded when uses `$this->out()` output. To load without this defaults childrens, use `$this->out(false)`.|
| `$this->redirect($url)` | string | Create a header to redirect to another page. |
## Routes
The ExacTI Phacil Framework is a simple router base to create a simple and consistent web navigation.
Without SEO URL, we invoke a page with *route* get parameter when contains a scheme folder/file of controller, like this: *http://example.com/index.php?route=folder/file*.
In a sample case, we have this controller:
```php
<?php
class ControllerFolderFile extends Controller {
public function index() {
echo "Index";
}
public function another() {
echo $this->foo($this->request->get['p']);
}
private function foo($parameter) {
return ($parameter != 0) ? "another" : "other";
}
}
```
If we access *index.php?route=folder/file* we see the "Index" message. But, like a tree, if we access *index.php?route=folder/file/another* obtains another function code, with "other" message.
Multiple Get parameters is simple and we can define normally, e.g.: *index.php?route=folder/file/another&p=2* to print "another" message.
Private and protected functions is only for internal use, if we tried to access *index.php?route=folder/file/foo*, the framework return 404 HTTP error.
### SEO URL
If you need a beautiful URL for SEO or other optimizations, you can use the url_alias database table. Is very simple and "translate" the routes in URL.
Execute this SQL in your database to create a url_alias table:
With the url_alias, the access to route *http://example.com/index.php?route=contact/contato* and *http://example.com/contact* is the same!(and very pretty!).
#### SEO URL without Database
You can create URL without a SQL Database configuration. For this you just need specify routes in the config file using the ***ROUTES*** constant with array content, like this:
```php
define('ROUTES', array(
'magic' => 'common/home/xml',
'json' => 'common/home/json'));
```
### Links
We have a function to create a strict and dynamic links automatic: `$this->url->link($route, $args = '', $connection = 'NONSSL')`. Is a simple function to generate internal links with correct URL encode.
In sample of this table above, if we have this code:
```php
echo $this->url->link('contact/contato');
```
We get this URL in output: *http://example.com/contact*
But if you don't have a route in url_alias table, returns the complete route.
```php
echo $this->url->link('catalog/products');
```
Return this URL in output: *http://example.com/index.php?route=catalog/products*
***Note:*** *It's necessary specify the config `config_seo_url` for correctly function of this URLs. If you use the SQL url_alias table, you need specify the `USE_DB_CONFIG` to true in config file.*
6 years ago
### Passing URI Segments to your Functions
Use the *'%'* character and its variations (see below) to create a route with wildcard. All contents in the URL will matches with wildcard is passed to your controller function as argument.
| Wildcard | Description |
| ----- | -----|
| %d | Matches any decimal digit equivalent to [0-9].|
| %w | Matches any letter, digit or underscore. Equivalent to [a-zA-Z0-9_]. Spaces or others character is not allowed. |
| %a | Matches any character in the valid ASCII range. Latin characters like *'ç'* or *'ã'* is not accepted. |
| % | Accept any character.|
##### Sample:
```php
define("ROUTES", array(
"produto/%d/%/promo" => "feriado/natal/presentes"
)
```
```php
<?php
class ControllerFeriadoNatal extends Controller {
public function presentes($id, $name) {
echo $id;
echo $name;
}
}
```
In this sample above, imagine the URL *http://yoursite.com/produto/**87**/**alfajor**/promo*, this URL is sending to function *presentes* values for `$id` and `$name` arguments in sequential method, in other words, the value of `$id` is set to `87` and `$name` to `alfajor`. The wildcard *%d* in router relative to `$id` argument define is only accepted number values.
In this moment, this resource is only available in constant ROUTES method. SQL routes not support wildcard at this moment.
The `$this->response->addHeader` is responsible to send a personalized HTTP header to browser, in this case specify the *Content-Type* information. The `$this->response->setOutput()` works for send output of the content of a variable, function, constant, etc., to the browser.
The config library in Phacil Framework obtains values to use in entire web app of: `$config` array in *config.php* file, the settings table in your configured database or both.
Is based in key->value mode with options like serialized value.
To use a configuration value, just call `$this->config->get('nameOfKey')`.
To storage a config value, use a SQL table called settings or an array.
If you need to register a class or other resource to use in your entire application, you can create using the file *registrations.php* in the **system** folder.
Use to specify a `$registry->set('name', $function);` with the function, class or method if you need. After this, just use `$this->name` to access this registry inside a controller or model.
#### Sample to register a simple class
Declare in /system/registrations.php
```php
<?php
// use for register aditionals
$criptoClass = new CriptoClass('salt');
$registry->set('cripto', $criptoClass);
```
Using in /controler/demo/sample.php
```php
<?php
class ControllerDemoSample extends Controller {
public function index() {
$value = 123;
$use = $this->cripto->function($value);
echo $use;
}
}
```
You can make registrations more complex too, for sample, use another database or a load call.
//see the load database method above for better comprehension
}
}
new DBne($registry);
```
Using in /controller/demo/sample.php
```php
class ControllerDemoSample extends Controller {
public function index() {
$this->test->query("SELECT * FROM mundo");
}
}
```
***Pay attention:*** *Use the registrations only for objects that you need to access from the entire application. E.g.: If you need to connect a one more database but you just use for one model, it's better to load just inside the model, for awesome performance.*
To add new classes or functions, you can put a folder in system directory with a autoload.php file. All autoload.php files are included to framework automatically.
### Use Composer
Composer is an application-level package manager for the PHP programming language that provides a standard format for managing dependencies of PHP software and required libraries.
To use Composer packages and autoloads, just configure your _composer.json_ with this vendor-dir: system/vendor.