### Basic Micro Application Setup
Source: https://github.com/phalcon/documentation/blob/master/docs/application-micro.md
This snippet demonstrates the basic setup of a Phalcon Micro application, including defining a GET route and handling requests.
```php
get(
'/invoices/view/{id}',
function ($id) {
echo "
#{$id}!
";
}
);
$app->handle(
$_SERVER["REQUEST_URI"]
);
```
--------------------------------
### Overloading setUp Method
Source: https://github.com/phalcon/documentation/blob/master/docs/unit-testing.md
Example of how to correctly overload the setUp method in a derived test class. It is crucial to call the parent::setUp() to ensure Phalcon initializes properly.
```php
protected function setUp(): void
{
parent::setUp();
//...
}
```
--------------------------------
### start
Source: https://github.com/phalcon/documentation/blob/master/docs/views.md
Starts the rendering process, enabling output buffering.
```APIDOC
## start
### Description
Starts the rendering process, enabling output buffering.
### Method
Not applicable (method call on View object)
### Endpoint
Not applicable
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```php
$view->start();
```
### Response
#### Success Response (200)
None
#### Response Example
None
```
--------------------------------
### Get Help for Project Creation Command
Source: https://github.com/phalcon/documentation/blob/master/docs/devtools.md
Displays detailed help and usage information for the `phalcon project` command, including arguments, options, and examples.
```bash
$ phalcon project --help
Phalcon DevTools (5.0.0)
Help:
Creates a project
Usage:
project [name] [type] [directory] [enable-webtools]
Arguments:
help Shows this help text
Example
phalcon project store simple
Options:
--name=s Name of the new project
--enable-webtools Determines if webtools should be enabled [optional]
--directory=s Base path on which project will be created [optional]
--type=s Type of the application to be generated (cli, micro, simple, modules)
--template-path=s Specify a template path [optional]
--template-engine=s Define the template engine, default phtml (phtml, volt) [optional]
--use-config-ini Use a ini file as configuration file [optional]
--trace Shows the trace of the framework in case of exception [optional]
--help Shows this help [optional]
```
--------------------------------
### Install Phalcon via APT
Source: https://github.com/phalcon/documentation/blob/master/docs/installation.md
Install the Phalcon PHP extension using apt-get after adding the necessary PPA.
```bash
sudo apt-get install php-phalcon5
```
--------------------------------
### Example Controller Definitions
Source: https://github.com/phalcon/documentation/blob/master/docs/application-micro.md
Defines sample controller classes for Users, Invoices, and Products.
Each controller includes `get` and `add` methods, representing typical API actions.
```php
setDefaultAction(
\Phalcon\Acl\Enum::DENY
);
// Register roles
$roles = [
"users" => new \Phalcon\Acl\Role("Users"),
"guests" => new \Phalcon\Acl\Role("Guests"),
];
foreach ($roles as $role) {
$acl->addRole($role);
}
// Private area components
$privateComponents = [
"companies" => ["index", "search", "new", "edit", "save", "create", "delete"],
"products" => ["index", "search", "new", "edit", "save", "create", "delete"],
"invoices" => ["index", "profile"],
];
foreach ($privateComponents as $componentName => $actions) {
$acl->addComponent(
new \Phalcon\Acl\Component($componentName),
$actions
);
}
// Public area components
$publicComponents = [
"index" => ["index"],
"about" => ["index"],
"session" => ["index", "register", "start", "end"],
"contact" => ["index", "send"],
];
foreach ($publicComponents as $componentName => $actions) {
$acl->addComponent(
new \Phalcon\Acl\Component($componentName),
$actions
);
}
// Grant access to public areas to both users and guests
foreach ($roles as $role) {
foreach ($publicComponents as $component => $actions) {
$acl->allow($role->getName(), $component, "*");
}
}
// Grant access to private area to role Users
foreach ($privateComponents as $component => $actions) {
foreach ($actions as $action) {
$acl->allow("Users", $component, $action);
}
}
```
--------------------------------
### Single/Multi-Module Application Setup
Source: https://github.com/phalcon/documentation/blob/master/docs/reproducible-tests.md
Demonstrates the basic setup for a Phalcon MVC application, including DI container and application instance creation. Remember to register your modules if applicable.
```php
setDI($container);
// register modules if any
$response = $application->handle(
$_SERVER["REQUEST_URI"]
);
echo $response->getContent();
```
--------------------------------
### Logger Setup for Excluding Adapters
Source: https://github.com/phalcon/documentation/blob/master/docs/logger.md
This code demonstrates the initial setup required before using the `excludeAdapters` functionality. It shows how to instantiate the logger with multiple stream adapters.
```php
$adapter1,
'remote' => $adapter2,
'manager' => $adapter3,
]
);
```
--------------------------------
### View File Example
Source: https://github.com/phalcon/documentation/blob/master/docs/tutorial-basic.md
This is an example of a Phalcon view file (`.phtml`). It demonstrates how to output HTML content and use the TagFactory to generate links.
```php
Hello!";
echo PHP_EOL;
echo PHP_EOL;
echo $this->tag->a('signup', 'Sign Up Here!');
```
--------------------------------
### Start a Session
Source: https://github.com/phalcon/documentation/blob/master/docs/session.md
Start the session using the start() method. This should typically be called early in your application's workflow. It returns a boolean indicating success or failure.
```php
'/tmp',
]
);
$session->setAdapter($files);
$session->start();
```
--------------------------------
### Install Phalcon via Homebrew on macOS (Binary)
Source: https://github.com/phalcon/documentation/blob/master/docs/installation.md
Install Phalcon using Homebrew by tapping the Phalcon extension repository and then installing the Phalcon package.
```bash
brew tap phalcon/extension https://github.com/phalcon/homebrew-tap
brew install phalcon
```
--------------------------------
### Start PHP Built-in Server
Source: https://github.com/phalcon/documentation/blob/master/docs/webserver-setup.md
Use this command to start the PHP built-in web server for development. Ensure your project has an entry point like `public/index.php`.
```bash
$(which php) -S localhost:8000 -t public .htrouter.php
```
--------------------------------
### Application Setup with Models and Controllers
Source: https://github.com/phalcon/documentation/blob/master/docs/reproducible-tests.md
Extends the basic MVC application setup by including definitions for a Controller and a Model. This is useful for testing application logic that involves these components.
```php
setDI($container);
class IndexController extends Controller
{
public function indexAction() {
/* your content here */
}
}
class Users extends Model
{
}
$response = $application->handle(
$_SERVER["REQUEST_URI"]
);
echo $response->getContent();
```
--------------------------------
### Start Profiling Entry
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_datamapper.md
Starts a profile entry for a given method.
```php
public function start( string $method ): void;
```
--------------------------------
### Basic ACL Setup and Querying
Source: https://github.com/phalcon/documentation/blob/master/docs/acl.md
Demonstrates how to set up roles, components, and access rules (allow/deny) in an in-memory ACL, and then query permissions using `isAllowed()` with various scenarios including wildcards.
```php
addRole('manager');
$acl->addRole('accounting');
$acl->addRole('guest');
// Add components
$acl->addComponent(
'admin',
[
'dashboard',
'users',
'view',
]
);
$acl->addComponent(
'reports',
[
'list',
'add',
'view',
]
);
$acl->addComponent(
'session',
[
'login',
'logout',
]
);
// Set up the `allow` list
$acl->allow('manager', 'admin', 'users');
$acl->allow('manager', 'reports', ['list', 'add']);
$acl->allow('*', 'session', '*');
$acl->allow('*', '*', 'view');
// Set up the `deny` list
$acl->deny('guest', '*', 'view');
// ....
// `true` - defined explicitly
$acl->isAllowed('manager', 'admin', 'dashboard');
// `true` - defined with wildcard
$acl->isAllowed('manager', 'session', 'login');
// `true` - defined with wildcard
$acl->isAllowed('accounting', 'reports', 'view');
// `false` - defined explicitly
$acl->isAllowed('guest', 'reports', 'view');
// `false` - default access level
$acl->isAllowed('guest', 'reports', 'add');
```
--------------------------------
### Get Request Data (GET/POST/REQUEST)
Source: https://github.com/phalcon/documentation/blob/master/docs/request.md
Retrieve the 'userEmail' field from the request data. This example shows how to get the value without any sanitization.
```php
get('userEmail');
```
--------------------------------
### Get Query Parameter
Source: https://github.com/phalcon/documentation/blob/master/docs/request.md
Retrieve the 'userEmail' field from the URL query string (GET parameters). This example shows retrieval without sanitization.
```php
getQuery('userEmail');
```
--------------------------------
### Micro Application Setup
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_mvc.md
Demonstrates how to initialize and configure a Phalcon Micro application, including defining routes and handling requests.
```APIDOC
## Micro Application Example
### Description
This example shows the basic setup for a Phalcon Micro application, including defining a GET route and handling a request.
### Usage
```php
$app = new \Phalcon\Mvc\Micro();
$app->get(
"/say/welcome/{name}",
function ($name) {
echo "Welcome $name!
";
}
);
$app->handle("/say/welcome/Phalcon");
```
```
--------------------------------
### Controller Example
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_mvc.md
Example of a controller class extending Phalcon\Mvc\Controller, demonstrating index, find, and save actions.
```php
dispatcher->forward(
[
"controller" => "people",
"action" => "index",
]
);
}
}
```
--------------------------------
### Install Composer Dependencies
Source: https://github.com/phalcon/documentation/blob/master/docs/testing-environment.md
Run this command to install or update project dependencies using Composer.
```bash
composer install
```
--------------------------------
### Create Controller Command Example
Source: https://github.com/phalcon/documentation/blob/master/docs/devtools.md
Example command to generate a controller named 'test' using Phalcon Devtools.
```bash
$ phalcon create-controller --name test
```
--------------------------------
### getOrCreateTransaction
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_mvc.md
Gets an existing transaction or creates a new one, optionally starting it.
```APIDOC
## getOrCreateTransaction
### Description
Create/Returns a new transaction or an existing one.
### Method
getOrCreateTransaction
### Parameters
- **autoBegin** (bool) - Optional. Determines if the transaction should be automatically started.
```
--------------------------------
### get
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_mvc.md
Retrieves a transaction, creating a new one if necessary and optionally starting it.
```APIDOC
## get
### Description
Returns a new \Phalcon\Mvc\Model\Transaction or an already created once. This method registers a shutdown function to rollback active connections.
### Method
get
### Parameters
- **autoBegin** (bool) - Optional. Determines if the transaction should be automatically started.
```
--------------------------------
### Compile and Install PCRE from Source
Source: https://github.com/phalcon/documentation/blob/master/docs/installation.md
Manually compile and install the PCRE library from source. This method is used when package managers are not available or preferred. It involves configuring, compiling, and installing the library, followed by creating symbolic links for system-wide access.
```bash
tar -xzvf pcre-8.42.tar.gz
cd pcre-8.42
./configure --prefix=/usr/local/pcre-8.42
make
make install
ln -s /usr/local/pcre-8.42 /usr/sbin/pcre
ln -s /usr/local/pcre-8.42/include/pcre.h /usr/include/pcre.h
```
--------------------------------
### Install Phalcon using PECL
Source: https://github.com/phalcon/documentation/blob/master/docs/upgrade.md
Use PECL to install the Phalcon extension. Specify a version if needed.
```bash
pecl install phalcon
// pecl install phalcon-5.4.0
```
--------------------------------
### Using Custom Storage Adapter
Source: https://github.com/phalcon/documentation/blob/master/docs/storage.md
Shows how to instantiate and use a custom storage adapter. Requires the custom adapter class to be defined.
```php
set('my-key', $data);
```
--------------------------------
### INI Configuration File Example
Source: https://github.com/phalcon/documentation/blob/master/docs/config.md
This is an example of an INI file structure. Sections represent top-level elements, and keys with a '.' separator create nested collections.
```ini
[database]
adapter = Mysql
host = localhost
username = scott
password = cheetah
dbname = test_db
[config]
adapter = ini
filePath = PATH_DATA"storage/config"
mode = 1
[models]
metadata.adapter = 'Memory'
```
--------------------------------
### Start View Rendering Output Buffering in Phalcon
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_mvc.md
Call `start` to begin the view rendering process by enabling output buffering. This is typically the first step before rendering views.
```php
$this->view->start();
```
--------------------------------
### Start Nginx Service
Source: https://github.com/phalcon/documentation/blob/master/docs/webserver-setup.md
Common commands to start the Nginx web server service on various Linux systems. The exact command may vary depending on the distribution and installation method.
```bash
start nginx
```
```bash
/etc/init.d/nginx start
```
```bash
service nginx start
```
--------------------------------
### Initialize Registry with Data
Source: https://github.com/phalcon/documentation/blob/master/docs/support-registry.md
Demonstrates how to create a new Registry object and populate it with initial data from an array. This is useful for setting up the registry with predefined values.
```php
[
'red',
'green',
'blue',
],
'year' => 1987,
];
$collection = new Registry($data);
```
--------------------------------
### get
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_mvc.md
Returns a new \Phalcon\Mvc\Model\Transaction or an already created one, optionally starting a new transaction if autoBegin is true.
```APIDOC
## get
### Description
Returns a new \Phalcon\Mvc\Model\Transaction or an already created one. If `autoBegin` is true, it starts a new transaction if one is not already active.
### Method
GET
### Endpoint
/transaction
### Parameters
#### Query Parameters
- **autoBegin** (bool) - Optional - If true, starts a new transaction if none is active.
### Response
#### Success Response (200)
- **transaction** (TransactionInterface) - The transaction object.
#### Response Example
```
--------------------------------
### Enable Phalcon Extension (Example Paths)
Source: https://github.com/phalcon/documentation/blob/master/docs/installation.md
Create a phalcon.ini file to enable the Phalcon extension. Paths may vary by distribution and PHP version.
```ini
extension=phalcon.so
```
--------------------------------
### Get Best Charset with Phalcon Request
Source: https://github.com/phalcon/documentation/blob/master/docs/request.md
Retrieve the best character set accepted by the browser, for example, utf-8.
```php
$charset = $request->getBestCharset();
```
--------------------------------
### Start Rendering Process
Source: https://github.com/phalcon/documentation/blob/master/docs/views.md
Begins the view rendering by enabling output buffering.
```php
public function start(): View
```
--------------------------------
### Get or Create Transaction
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_mvc.md
Retrieves an existing transaction or creates a new one if none exists. It can optionally start the transaction automatically.
```php
public function get( bool $autoBegin = bool ): TransactionInterface;
public function getOrCreateTransaction( bool $autoBegin = bool ): TransactionInterface;
```
--------------------------------
### Set and Get Session Name
Source: https://github.com/phalcon/documentation/blob/master/docs/session.md
Set a custom session name using `setName()` before starting the session. Retrieve the current session name with `getName()`.
```php
'/tmp',
]
);
$session
->setAdapter($files)
->setName('phalcon-app')
->start();
echo $session->getName(); // 'phalcon-app'
```
--------------------------------
### Instantiate MySQL, PostgreSQL, and SQLite Database Adapters
Source: https://github.com/phalcon/documentation/blob/master/docs/db-layer.md
Demonstrates creating connections to MySQL, PostgreSQL, and SQLite databases using their respective adapter classes and configuration arrays. Ensure the configuration array contains the necessary parameters for each adapter.
```php
'127.0.0.1',
'username' => 'mike',
'password' => 'sigma',
'dbname' => 'test_db',
];
$connection = new Mysql($config);
$config = [
'host' => 'localhost',
'username' => 'postgres',
'password' => 'secret1',
'dbname' => 'template',
];
$connection = new Postgresql($config);
$config = [
'dbname' => '/path/to/database.db',
];
$connection = new Sqlite($config);
```
--------------------------------
### Set and Get Session ID
Source: https://github.com/phalcon/documentation/blob/master/docs/session.md
Set a custom session ID using `setId()` before starting the session. Retrieve the current session ID with `getId()`.
```php
'/tmp',
]
);
$session
->setAdapter($files)
->setId('phalcon-id')
->start();
echo $session->getId(); // 'phalcon-id'
```
--------------------------------
### Install Phalcon via pkg on FreeBSD
Source: https://github.com/phalcon/documentation/blob/master/docs/installation.md
Install the Phalcon PHP extension on FreeBSD using the pkg package manager.
```bash
pkg install php80-phalcon5
```
--------------------------------
### Get Client IP Address with Phalcon Request
Source: https://github.com/phalcon/documentation/blob/master/docs/request.md
Retrieve the client's IP address using the getClientAddress() method. Example IP: 201.245.53.51.
```php
$ipAddress = $request->getClientAddress();
```
--------------------------------
### Get Server IP Address with Phalcon Request
Source: https://github.com/phalcon/documentation/blob/master/docs/request.md
Retrieve the server's IP address using the getServerAddress() method. Example IP: 192.168.0.100.
```php
$ipAddress = $request->getServerAddress();
```
--------------------------------
### Configure Bootstrap File (public/index.php)
Source: https://github.com/phalcon/documentation/blob/master/docs/tutorial-basic.md
Sets up the loader, dependency injection container, and application instance. Handles incoming requests and exceptions. Ensure the base and app paths are correctly defined.
```php
registerDirs(
[
APP_PATH . '/controllers/',
APP_PATH . '/models/',
]
);
$loader->register();
$container = new FactoryDefault();
$container->set(
'view',
function () {
$view = new View();
$view->setViewsDir(APP_PATH . '/views/');
return $view;
}
);
$container->set(
'url',
function () {
$url = new Url();
$url->setBaseUri('/');
return $url;
}
);
$application = new Application($container);
try {
// Handle the request
$response = $application->handle(
$_SERVER["REQUEST_URI"]
);
$response->send();
} catch (\Exception $e) {
echo 'Exception: ', $e->getMessage();
}
```
--------------------------------
### ORM Setup with Events and Table Creation
Source: https://github.com/phalcon/documentation/blob/master/docs/reproducible-tests.md
Demonstrates setting up Phalcon's ORM with a database connection, event manager, and model definitions. It includes creating a 'user' table if it doesn't exist and a method to create a new user.
```php
'localhost',
'username' => 'root',
'password' => '',
'dbname' => 'test',
]
);
$connection->setEventsManager($eventsManager);
$eventsManager->attach(
'db:beforeQuery',
function ($event, $connection) {
echo $connection->getSqlStatement(), '
' . PHP_EOL;
}
);
$container['db'] = $connection;
$container['modelsManager'] = new ModelsManager();
$container['modelsMetadata'] = new ModelsMetaData();
if (true !== $connection->tableExists('user', 'test')) {
$connection->execute(
'CREATE TABLE user (
id integer primary key auto_increment,
email varchar(120) not null
)'
);
}
class User extends Model
{
public $id;
public $email;
public static function createNewUserReturnId()
{
$newUser = new User();
$newUser->email = 'test';
if (false === $newUser->save()) {
return false;
}
return $newUser->id;
}
}
echo User::createNewUserReturnId();
```
--------------------------------
### Registry Usage Example
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_support.md
Demonstrates how to set, get, check existence, and unset values in a Phalcon Registry using both object property and array access syntax.
```php
$registry = new \Phalcon\Registry();
// Set value
$registry->something = "something";
// or
$registry["something"] = "something";
// Get value
$value = $registry->something;
// or
$value = $registry["something"];
// Check if the key exists
$exists = isset($registry->something);
// or
$exists = isset($registry["something"]);
// Unset
unset($registry->something);
// or
unset($registry["something"]);
```
--------------------------------
### Psalm Analysis Output Example
Source: https://github.com/phalcon/documentation/blob/master/docs/static-analysis.md
This is an example of the output you might see when running Psalm. If no errors are found, it will indicate success.
```bash
Scanning files...
Analyzing files...
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 60 / 95 (63%)
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
------------------------------
No errors found!
------------------------------
Checks took 0.80 seconds and used 214.993MB of memory
Psalm was able to infer types for 92.9630% of the codebase
```
--------------------------------
### Define Invoice Routes with a Collection
Source: https://github.com/phalcon/documentation/blob/master/docs/application-micro.md
Use MicroCollection to group routes for a specific handler and prefix. This example defines GET routes for displaying, adding, updating, and deleting invoices.
```php
setHandler(new InvoicesController());
$invoices->setPrefix('/invoices');
$invoices->get('/get/{id}', 'displayAction');
$invoices->get('/add/{payload}', 'addAction');
$invoices->get('/update/{id}', 'updateAction');
$invoices->get('/delete/{id}', 'deleteAction');
$app->mount($invoices);
```
--------------------------------
### Basic Dispatcher Setup and Execution
Source: https://github.com/phalcon/documentation/blob/master/docs/dispatcher.md
This snippet demonstrates the basic setup of the Phalcon Dispatcher, including setting the DI container, controller name, action name, and parameters, followed by executing the dispatch process.
```php
setDI($container);
$dispatcher->setControllerName("posts");
$dispatcher->setActionName("index");
$dispatcher->setParams([]);
$controller = $dispatcher->dispatch();
```
--------------------------------
### Start Docker Environment (Local - No Port Exposure)
Source: https://github.com/phalcon/documentation/blob/master/docs/testing-environment.md
Start the Docker environment using the local configuration, which does not expose ports to the host. This is useful for running multiple environments concurrently.
```bash
docker compose -f docker-compose-local.yml up -d
```
--------------------------------
### Init Method
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_factory.md
Initializes the factory with provided services or adds new ones.
```php
protected function init( array $services = [] ): void;
```
--------------------------------
### Map Route with Multiple HTTP Methods
Source: https://github.com/phalcon/documentation/blob/master/docs/application-micro.md
The mapVia method allows mapping a single route pattern to a handler using an array of HTTP methods. This example maps '/invoices' to 'indexAction' for both POST and GET requests.
```php
$collection->mapVia(
"/invoices",
"indexAction",
[
"POST",
"GET"
],
"invoices"
);
```
--------------------------------
### Get Request Headers With Custom Authorization Resolver
Source: https://github.com/phalcon/documentation/blob/master/docs/request.md
Illustrates setting up a custom authorization listener and DI container to process a 'Negotiate' authorization type. This example shows how to attach an event listener to the request component and retrieve headers with custom authorization logic.
```php
$data['server']['CUSTOM_KERBEROS_AUTH'],
];
}
}
$_SERVER['CUSTOM_KERBEROS_AUTH'] = 'Negotiate '.
'a87421000492aa874209af8bc028';
$di = new Di();
$di->set(
'eventsManager',
function () {
$manager = new Manager();
$manager->attach(
'request',
new NegotiateAuthorizationListener()
);
return $manager;
}
);
$request = new Request();
$request->setDI($di);
print_r(
$request->getHeaders()
);
```
--------------------------------
### Example YAML Configuration
Source: https://github.com/phalcon/documentation/blob/master/docs/config.md
A sample YAML file structure for application configuration, including settings for the app, models, and loggers.
```yaml
app:
baseUri: /
env: 3
name: PHALCON
timezone: UTC
url: http://127.0.0.1
version: 0.1
time: 1562960897.712697
models:
metadata:
adapter: Memory
loggers:
handlers:
0:
name: stream
1:
name: redis
```
--------------------------------
### Initialize and Render View
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_mvc.md
Demonstrates how to initialize the Phalcon View component, set the views directory, start the view, render a specific view file, and retrieve its content.
```php
use Phalcon\Mvc\View;
$view = new View();
// Setting views directory
$view->setViewsDir("app/views/");
$view->start();
// Shows recent posts view (app/views/posts/recent.phtml)
$view->render("posts", "recent");
$view->finish();
// Printing views output
echo $view->getContent();
```
--------------------------------
### Manage Model Transactions with Phalcon Mvc Model Transaction Manager
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_mvc.md
Demonstrates how to use the Phalcon Mvc Model Transaction Manager to handle database transactions. This example shows how to get a transaction, associate models with it, save models, and commit or rollback the transaction based on save outcomes.
```php
use Phalcon\Mvc\Model\Transaction\Failed;
use Phalcon\Mvc\Model\Transaction\Manager;
try {
$transactionManager = new Manager();
$transaction = $transactionManager->get();
$robot = new Robots();
$robot->setTransaction($transaction);
$robot->name = "WALL·E";
$robot->created_at = date("Y-m-d");
if ($robot->save() === false) {
$transaction->rollback("Can't save robot");
}
$robotPart = new RobotParts();
$robotPart->setTransaction($transaction);
$robotPart->type = "head";
if ($robotPart->save() === false) {
$transaction->rollback("Can't save robot part");
}
$transaction->commit();
} catch (Failed $e) {
echo "Failed, reason: ", $e->getMessage();
}
```
--------------------------------
### Install Phalcon Framework
Source: https://github.com/phalcon/documentation/blob/master/docs/environments-devilbox.md
Navigate into the newly created vhost directory and use the Phalcon CLI to create a new Phalcon project. This command assumes the Phalcon CLI is available within the container.
```bash
devilbox@php-8.0 in /shared/httpd $ cd my-phalcon
devilbox@php-8.0 in /shared/httpd/my-phalcon $ phalcon project phalconphp
```
--------------------------------
### Start Session
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_session.md
Starts the session. If headers have already been sent, the session will not be started.
```APIDOC
## start
### Description
Starts the session (if headers are already sent the session will not be
started)
### Method
public function start(): bool
```
--------------------------------
### URL Example for Typed Parameters
Source: https://github.com/phalcon/documentation/blob/master/docs/controllers.md
Illustrates a valid URL for a controller action with typed parameters and an example of an invalid URL that would cause type-mismatch errors.
```text
/invoices/list/2/10
```
```text
/invoices/list/wrong-value/another-wrong-value
```
--------------------------------
### Start Built-in PHP Server
Source: https://github.com/phalcon/documentation/blob/master/docs/tutorial-rest.md
Command to start the PHP built-in server on localhost:8000, serving files from the current directory and using the specified router.
```bash
$(which php) -S localhost:8000 -t / .htrouter.php
```
--------------------------------
### Example: Add and Check Asset
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_assets.md
Demonstrates how to create a collection, add an asset, and then check if the asset exists in the collection.
```php
use Phalcon\Assets\Asset;
use Phalcon\Assets\Collection;
$collection = new Collection();
$asset = new Asset("js", "js/jquery.js");
$collection->add($asset);
$collection->has($asset); // true
```
--------------------------------
### Start Session
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_session.md
Starts the session. Note that the session will not be started if headers have already been sent.
```php
public function start(): bool;
```
--------------------------------
### Install Phalcon via PECL
Source: https://github.com/phalcon/documentation/blob/master/docs/installation.md
Use PECL to install Phalcon on Linux, macOS, or Windows. Ensure you have PECL/PEAR installed.
```bash
pecl channel-update pecl.php.net
pecl install phalcon
```
--------------------------------
### Install Phalcon Devtools Globally
Source: https://github.com/phalcon/documentation/blob/master/docs/devtools.md
Installs the Phalcon Devtools globally using Composer. Ensure Composer is installed first.
```bash
composer global require phalcon/devtools
```
--------------------------------
### Zephir Init Command
Source: https://github.com/phalcon/documentation/blob/master/docs/testing-environment.md
Initializes a new Zephir extension.
```bash
init
```
--------------------------------
### Install Phalcon Devtools Locally
Source: https://github.com/phalcon/documentation/blob/master/docs/devtools.md
Installs the Phalcon Devtools within a specific project using Composer. Ensure Composer is installed first.
```bash
composer require phalcon/devtools
```
--------------------------------
### Create and Save a New Model Instance
Source: https://github.com/phalcon/documentation/blob/master/docs/db-models.md
Demonstrates how to instantiate a model, set its properties, and save it to the database. It includes error handling to display validation messages if the save operation fails.
```php
inv_cst_id = 1;
$invoice->inv_status_flag = 1;
$invoice->inv_title = 'Invoice for ACME Inc.';
$invoice->inv_total = 100;
$invoice->inv_created_at = '2019-12-25 01:02:03';
$result = $invoice->save();
if (false === $result) {
echo 'Error saving Invoice: ';
$messages = $invoice->getMessages();
foreach ($messages as $message) {
echo $message . PHP_EOL;
}
} else {
echo 'Record Saved';
}
```
--------------------------------
### begin
Source: https://github.com/phalcon/documentation/blob/master/docs/db-layer.md
Starts a new transaction. Supports nesting.
```APIDOC
## begin
### Description
Starts a transaction in the connection. Supports nesting.
### Method Signature
```php
public function begin(bool $nesting = true): bool
```
```
--------------------------------
### Initialize Micro App and Set Model Binder
Source: https://github.com/phalcon/documentation/blob/master/docs/application-micro.md
Initializes a new Micro application instance and sets a model binder with cache.
```php
$micro = new Micro($di);
$micro->setModelBinder(
new Binder(),
'cache'
);
```
--------------------------------
### Check if Session Started
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_session.md
Determines if the session has already been started.
```php
public function exists(): bool;
```
--------------------------------
### Set Up Database Connection Service
Source: https://github.com/phalcon/documentation/blob/master/docs/tutorial-basic.md
Configure the database connection as a service in the dependency injection container. Adjust host, username, password, and dbname for your environment.
```php
set(
'db',
function () {
return new Mysql(
[
'host' => '127.0.0.1',
'username' => 'root',
'password' => 'secret',
'dbname' => 'tutorial',
]
);
}
);
```
--------------------------------
### Example Logged SELECT Statement with Bound Parameters
Source: https://github.com/phalcon/documentation/blob/master/docs/db-layer.md
This example shows a logged SELECT statement, including the SQL query and the bound parameters in JSON format.
```text
[2019-12-25 01:02:03][INFO] SELECT `co_customers`.`cst_id`,
...,
FROM `co_customers`
WHERE LOWER(`co_customers`.`cst_email`) = :cst_email
LIMIT :APL0 - [{"emp_email":"team@phalcon.ld","APL0":1}]
```
--------------------------------
### Default Route Matching Example
Source: https://github.com/phalcon/documentation/blob/master/docs/tutorial-vokuro.md
Illustrates how a URL like /profiles/search is mapped to a specific controller action.
```bash
/profiles/search
to
/src/Controllers/ProfilesController.php -> searchAction
```
--------------------------------
### get
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_mvc.md
Maps a route to a handler that only matches if the HTTP method is GET.
```APIDOC
## GET /:routePattern
### Description
Maps a route to a handler that only matches if the HTTP method is GET.
### Method
GET
### Endpoint
/:routePattern
### Parameters
#### Path Parameters
- **routePattern** (string) - Required - The pattern of the route.
- **handler** (callable) - Required - The handler for the route.
- **name** (string) - Optional - The name of the route.
### Response
#### Success Response (200)
- **CollectionInterface** (object) - The collection interface.
```
--------------------------------
### Initializing Volt Compiler
Source: https://github.com/phalcon/documentation/blob/master/docs/volt.md
Shows how to initialize the Volt compiler as a stand-alone component. Options can be set on the compiler instance.
```php
setOptions(
[
// ...
]
);
```
--------------------------------
### Phalcon\Cli\Dispatcher Example
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_cli.md
Example of how to use the Phalcon\Cli\Dispatcher to handle CLI commands.
```APIDOC
## Phalcon\Cli\Dispatcher Example
### Description
Dispatching is the process of taking the command-line arguments, extracting
the module name, task name, action name, and optional parameters contained in
it, and then instantiating a task and calling an action on it.
### Code Example
```php
use Phalcon\Di\Di;
use Phalcon\Cli\Dispatcher;
$di = new Di();
$dispatcher = new Dispatcher();
$dispatcher->setDi($di);
$dispatcher->setTaskName("posts");
$dispatcher->setActionName("index");
$dispatcher->setParams([]);
$handle = $dispatcher->dispatch();
```
```
--------------------------------
### Select OptGroupStart Method
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_html.md
Protected method to start an option group tag with a label and attributes.
```php
protected function optGroupStart( string $label, array $attributes ): string;
```
--------------------------------
### Check Zephir Installation
Source: https://github.com/phalcon/documentation/blob/master/docs/testing-environment.md
Run this command to verify that Zephir is installed and accessible in the environment.
```bash
zephir
```
--------------------------------
### Map GET Route
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_mvc.md
Maps a route to a handler that only matches if the HTTP method is GET.
```php
public function get( string $routePattern, mixed $handler ): RouteInterface;
```
--------------------------------
### Controller Initialization with initialize()
Source: https://github.com/phalcon/documentation/blob/master/docs/controllers.md
Use the `initialize()` method to perform setup tasks before an action is executed. This method is called after the `beforeExecuteRoute` event.
```php
tag->setTitle('Invoices Management');
}
public function listAction(int $page = 1, int $perPage = 25)
{
}
}
```
--------------------------------
### Load Logger with Configuration
Source: https://github.com/phalcon/documentation/blob/master/docs/logger.md
Use the `load` method to create a logger based on a configuration array. This example configures two stream adapters, 'main' and 'admin', for different logging purposes.
```php
"prod-logger",
"options" => [
"adapters" => [
"main" => [
"adapter" => "stream",
"name" => "/storage/logs/main.log",
"options" => []
],
"admin" => [
"adapter" => "stream",
"name" => "/storage/logs/admin.log",
"options" => []
],
],
],
];
$serializerFactory = new SerializerFactory();
$adapterFactory = new AdapterFactory();
$loggerFactory = new LoggerFactory($adapterFactory);
$logger = $loggerFactory->load($config);
```
--------------------------------
### getContentType() - Get Request Content Type
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_http.md
Gets the content type with which the request was made.
```APIDOC
## GET getContentType
### Description
Gets content type which request has been made
### Method
GET
### Endpoint
N/A (Method of a class)
### Parameters
None
### Response
#### Success Response (200)
- **string | null** - The content type of the request or null if not set.
```
--------------------------------
### Initialize Form with Elements
Source: https://github.com/phalcon/documentation/blob/master/docs/forms.md
Demonstrates initializing a form by adding various elements like Text and Select to it. The Select element is configured with data from a model and specific display options.
```php
add(
new Text(
'nameLast'
)
);
$this->add(
new Text(
'nameFirst'
)
);
$this->add(
new Select(
'phoneType',
PhoneTypes::find(),
[
'emptyText' => 'Select one...',
'emptyValue' => '',
'useEmpty' => true,
'using' => [
'typ_id',
'typ_name',
],
]
)
);
}
}
```
--------------------------------
### Phalcon\Mvc\Model\MetaData\Redis Constructor Example
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_mvc.md
Example of instantiating the Redis adapter with connection and lifetime options.
```php
use Phalcon\Mvc\Model\MetaData\Redis;
$metaData = new Redis(
[
"host" => "127.0.0.1",
"port" => 6379,
"persistent" => 0,
"lifetime" => 172800,
"index" => 2,
]
);
```
--------------------------------
### Creating YAML Configuration Instance with ConfigFactory
Source: https://github.com/phalcon/documentation/blob/master/docs/config.md
Illustrates using the ConfigFactory's newInstance method to create a Yaml config adapter with a specified file and callbacks.
```php
function($value) {
return APPROOT . $value;
},
];
$config = $factory->newinstance('yaml', $fileName, $callbacks);
```
--------------------------------
### Example Output of Collected Responses
Source: https://github.com/phalcon/documentation/blob/master/docs/events.md
The expected output when collecting responses from the previous example.
```bash
[
0 => 'first response',
1 => 'second response',
]
```
--------------------------------
### Custom DI Container with Services
Source: https://github.com/phalcon/documentation/blob/master/docs/application-micro.md
Demonstrates creating a custom DI container and registering services, such as a configuration adapter, before passing it to the Micro application.
```php
set(
'config',
function () {
return new Ini(
'config.ini'
);
}
);
$app = new Micro($container);
$app->get(
'/',
function () use ($app) {
echo $app
->config
->app_name;
}
);
$app->post(
'/contact',
function () use ($app) {
$app
->flash
->success('++++++')
;
}
);
```
--------------------------------
### Create INI Configuration Instance with newInstance
Source: https://github.com/phalcon/documentation/blob/master/docs/config.md
Demonstrates creating a new INI configuration instance using the ConfigFactory's newInstance() method. Configuration parameters, including the mode, can be passed in an array.
```php
INI_SCANNER_NORMAL,
];
$config = $factory->newinstance('ini', $fileName, $params);
```
--------------------------------
### Install Phalcon via ports on FreeBSD
Source: https://github.com/phalcon/documentation/blob/master/docs/installation.md
Compile and install Phalcon on FreeBSD from the ports tree.
```bash
cd /usr/ports/www/phalcon5
make install clean
```
--------------------------------
### Model Initialization with Behaviors
Source: https://github.com/phalcon/documentation/blob/master/docs/db-models.md
Demonstrates how to add a Timestampable behavior to a model during initialization to automatically manage creation and update timestamps.
```php
addBehavior(
new Timestampable(
[
'onCreate' => [
'field' => 'inv_created_at',
'format' => 'Y-m-d H:i:s',
],
]
)
);
}
}
```
--------------------------------
### Get Write Database Connection
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_mvc.md
Gets the internal database connection used for writing data.
```php
public function getWriteConnection(): AdapterInterface;
```
--------------------------------
### Get Read Database Connection
Source: https://github.com/phalcon/documentation/blob/master/docs/api/phalcon_mvc.md
Gets the internal database connection used for reading data.
```php
public function getReadConnection(): AdapterInterface;
```
--------------------------------
### Setting up and using Dependency Injection
Source: https://github.com/phalcon/documentation/blob/master/docs/di.md
This example demonstrates how to set up a Dependency Injection container in Phalcon, register services like 'db', 'filter', and 'session', and then use these services within a component. It shows how a component can request dependencies from the container via its constructor.
```php
container = $container;
}
public function calculate()
{
$connection = $this
->container
->get('db')
;
}
public function view($id)
{
$filter = $this
->container
->get('filter')
;
$id = $filter->sanitize($id, null, 'int');
$connection = $this
->container
->getShared('db')
;
}
}
$container = new Di();
$container->set(
'db',
function () {
return new Mysql(
[
'host' => 'localhost',
'username' => 'root',
'password' => 'secret',
'dbname' => 'tutorial',
]
);
}
);
$container->set(
'filter',
function () {
return new Filter();
}
);
$container->set(
'session',
function () {
return new Session();
}
);
$invoice = new InvoiceComponent($container);
$invoice->calculate();
```
--------------------------------
### Method Declaration Examples
Source: https://github.com/phalcon/documentation/blob/master/docs/coding-standard.md
Illustrates different method declarations including abstract, final, and static methods, emphasizing the placement of keywords and visibility.
```zephir
abstract public function getElement() -> var;
final public function getElement() -> var;
public static function getElement() -> var;
```