PHPackages                             adhocore/phalcon-ext - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. adhocore/phalcon-ext

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

adhocore/phalcon-ext
====================

Miscellaneous phalcon adapters, extensions and utilities

0.1.0(6y ago)47961↓94.1%3[4 issues](https://github.com/adhocore/phalcon-ext/issues)[1 PRs](https://github.com/adhocore/phalcon-ext/pulls)MITPHPPHP &gt;=7.0CI failing

Since Jun 18Pushed 3y ago4 watchersCompare

[ Source](https://github.com/adhocore/phalcon-ext)[ Packagist](https://packagist.org/packages/adhocore/phalcon-ext)[ RSS](/packages/adhocore-phalcon-ext/feed)WikiDiscussions main Synced today

READMEChangelog (10)Dependencies (6)Versions (15)Used By (0)

adhocore/phalcon-ext
--------------------

[](#adhocorephalcon-ext)

Useful phalcon adapters, middlewares, extensions and utilities!

> Supports phalcon v4.

[![Travis Build](https://camo.githubusercontent.com/d5e19d65317817c965f9ca7d89f4dc5375b8c2d41da8075465e40b4577cd2d07/68747470733a2f2f7472617669732d63692e636f6d2f6164686f636f72652f7068616c636f6e2d6578742e7376673f6272616e63683d6d6173746572)](https://travis-ci.com/adhocore/phalcon-ext?branch=master)[![Latest Version](https://camo.githubusercontent.com/5b03553a8f22f4c3ead0cfbd3f243a803f03cc0c0e27b65df800e5a2532ba24a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f6164686f636f72652f7068616c636f6e2d6578742e7376673f7374796c653d666c61742d737175617265)](https://github.com/adhocore/phalcon-ext/releases)[![Scrutinizer CI](https://camo.githubusercontent.com/5d6e2aa741109af0fd045b1b1f2c6c4e7aaaa24970d3dae81b51175cf041962e/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f6164686f636f72652f7068616c636f6e2d6578742e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/adhocore/phalcon-ext/?branch=master)[![Codecov branch](https://camo.githubusercontent.com/1a7abfa2f6614669dd995c232119c03db3386507818b9054920a6e6577c41e6e/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f6164686f636f72652f7068616c636f6e2d6578742f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://codecov.io/gh/adhocore/phalcon-ext)[![StyleCI](https://camo.githubusercontent.com/402b26f74618e6459b039eae37ef7186a5d5a6bcfcdf8cdc0a006564e0da6f52/68747470733a2f2f7374796c6563692e696f2f7265706f732f3133363136363934372f736869656c64)](https://styleci.io/repos/136166947)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![Tweet](https://camo.githubusercontent.com/cb820a0ecc9645168e33b03925d7f14691262ddbaeaf66a0a91697803d0cba2d/68747470733a2f2f696d672e736869656c64732e696f2f747769747465722f75726c2f687474702f736869656c64732e696f2e7376673f7374796c653d736f6369616c)](https://twitter.com/intent/tweet?text=Adapters+middlewares+extensions+and+utilities+missing+in+phalcon+framework&url=https://github.com/adhocore/phalcon-ext&hashtags=php,phalcon,extension,middleware)[![Support](https://camo.githubusercontent.com/6687993dc9b60228356720a501b7c197c8c9a82194cac1b1c72d0dea95e6ad32/68747470733a2f2f696d672e736869656c64732e696f2f7374617469632f76313f6c6162656c3d537570706f7274266d6573736167653d254532253944254134266c6f676f3d476974487562)](https://github.com/sponsors/adhocore)

Installation
------------

[](#installation)

```
composer require adhocore/phalcon-ext
```

### What's included

[](#whats-included)

**Cache**

- [Redis](#cacheredis)

**Cli**

- [Extension](#cliextension)
- [Middleware](#climiddlewaretrait)
- [Scheduling](#clitaskscheduletask)

**Db**

- [Extension](#dbextension)
- [Logger](#dblogger)

**Di**

- [Extension](#diextension)
- [Provider](#diprovidesdi)

**Http**

- [Base Middleware](#httpbasemiddleware)
- [ApiAuth Middleware](#httpmiddlewareapiauth)
- [Cache Middleware](#httpmiddlewarecache)
- [Throttle Middleware](#httpmiddlewarethrottle)

**Logger**

- [Echo Logger](#loggerechologger)
- [File Logging](#loggerlogstofile)

**Mail**

- [Mailer](#mailmailer)
- [Mail](#mailmail)
- [Mailable](#mailmailable)
- [Logger](#maillogger)

**Util**

- [Opcache Primer](#utilopcacheprimer)

**Validation**

- [Validation Wrapper](#validationvalidation)
- [Db Existence Validator](#validationexistence)

**View**

- [Twig](#viewtwig)

---

### Cache.Redis

[](#cacheredis)

Extends `Phalcon\Cache\Backend\Redis` to allow access over the underlying redis binding.

#### Setup

[](#setup)

```
$di->setShared('redis', function () {
    return new \PhalconExt\Cache\Redis(new \Phalcon\Cache\Frontend\None(['lifetime' => 0]));
});

// Call native \Redis methods like:
$di->get('redis')->getConnection()->hGet();
$di->get('redis')->getConnection()->info();
```

---

### Cli.Extension

[](#cliextension)

Definitely check how it works in [adhocore/cli](https://github.com/adhocore/cli) and how it is integrated &amp; used in [example/cli](./example/cli), [example/MainTask.php](./example/MainTask.php)

#### Setup

[](#setup-1)

```
$di = new PhalconExt\Di\FactoryDefault;

$di->setShared('dispatcher', Phalcon\Cli\Dispatcher::class);
$di->setShared('router', Phalcon\Cli\Router::class);

$di->setShared('config', new Phalcon\Config([
    'console' => [
        'tasks' => [
            // Register your tasks here: 'name' => class
            // You will define their options/arguments in respective `onConstruct()`
            'main' => Your\MainTask::class,
        ],
    ],
]));

$console = new PhalconExt\Cli\Console($di, 'MyApp', 'v1.0.1');

// Or if you have your own Console extends, just use the trait
class YourConsole extends \Phalcon\Cli\Console
{
    use PhalconExt\Cli\Extension;
}
```

#### command(string $command, string $descr = '', bool $allowUnknown = false): Ahc\\Cli\\Command

[](#commandstring-command-string-descr---bool-allowunknown--false-ahcclicommand)

You can register command in the bootstrap if few or you can organise them in `SomeTask::onConstruct()` like so:

```
class MainTask extends Phalcon\Cli\Task
{
    public function onConstruct()
    {
        ($console = $this->getDI()->get('console'))
            ->command('main', 'Main task ...', false)
                ->arguments(' [optional:default]');
                ->option('-s --stuff', 'Description', 'callable:filter', 'default')
                ->tap($console) // for fluency
            ->schedule('7-9 * */9 * *')
            ->command('main:other', ...)
                ->option('')
                ->option('')
                ->tap($console)
            ->schedule('@5mintues') // @10minutes, @15minutes, @weekly, @daily, @yearly, @hourly ...
        ;
    }

    public function mainAction()
    {
        $io = $this->interactor;

        // Access defined args/opts for writing to terminal:
        $io->write($this->command->requiredPath, true);
        $io->write($this->command->stuff, true);
    }
}
```

Now everytime you run command `php cli.php main main the-path --stuff whatever`, it will print `the-path` and `whatever`! `cli.php` can be anything of your choosing that should be equivalent to [example/cli](./example/cli).

#### initTasks(void): self

[](#inittasksvoid-self)

Inits the loadable tasks. It is done automatically if you have listed them in `console.tasks` config (see Setup section above). If you have loaded tasks dyanamically or late in the process call it manually: `$console->initTasks()`.

#### Cli.MiddlewareTrait

[](#climiddlewaretrait)

Enables you to define, register and fire middlewares for the cli in simplest possible way! `PhalconExt/Cli/Middleware/Factory` is registered by default for convenience. It injects relevant command instance (`Ahc\Cli\Input\Command`) to DI and is auto triggered for `--help`, `--version`.

**Define middleware**

```
class HelloConsole
{
    // Prints hello every time you run a console cmd, just before execution
    public function before(PhalconExt\Cli\Console $console)
    {
        $console->getDI()->get('interactor')->bgGreenBold('Hello', true);

        return true; // Indicates success and no-objection!
    }
}
```

**Register/retrieve middleware(s)**

```
// Single:
$console->middleware(HelloConsole::class);

// Multiple:
$console->middlewares([HelloConsole::class, Another::class]);

// Get em: (It already contains PhalconExt/Cli/Middleware/Factory)
$console->middlewares(); // array
```

**Firing middlewares**

You dont have to. The `before` and `after` methods of all middlewares are automatically invoked as console lifecycle event.

### Cli.Task.ScheduleTask

[](#clitaskscheduletask)

Being factory feature of `adhocore/phalcon-ext` it is auto loaded so you dont have to put in config's `console.tasks` array.

It provides for commands `schedule:list` (or `schedule list`) and `schedule:run` or `schedule run` to respectively list all scheduled commands and run all commands due at that specific moment.

Registering tasks to be scheduled is a cheese too. Check `command()` section above, you can schedule a task in fluent interface like so:

```
$console
    ->command('task:action', ...)
        ->arguments(...)->option(...)
        ->tap($console)
    ->schedule('crontab expression') // You can also use humanly phrases: @daily, @hourly
;
```

As you can see, all you need to do in crontab is add the entry: `* * * * * php /path/to/your/phalcon-app-using-phalcon-ext/src/cli.php schedule:run`... and manage everything here in the code!

#### Caution

[](#caution)

Any tasks scheduled to run by automation like this should preferably **not** define required arguments or options of the form ``, as firstly they are not validated when being run as scheduled task, and secondly the philosphy of scheduling is to register single crontab script `* * * * * php /app/src/cli.php schedule:run` with no any args/options. (and these are made to run unattended if you want third point!)

However if you insist, it is possible to append `--option-name value` after `schedule:run` segment but this value goes to all of the due tasks runnable at the moment. They all can read it with `$this->command->optionName`.

---

### Db.Extension

[](#dbextension)

#### Setup

[](#setup-2)

```
$di->setShared('config', new \Phalcon\Config([
    'database' => [
        'driver' => 'sqlite',
        'dbname' => __DIR__ . '/.var/db.db',
    // ... other options (see phalcon &/or pdo docs)
    ],
]);

$di->setShared('db', function () {
    // Can use Mysql or Postgresql too
    return (new \PhalconExt\Db\Sqlite($this->get('config')->toArray()['database']));
});

// Or if you have your own already, just use the trait
class YourDb extends \Phalcon\Db\Adapter
{
    use PhalconExt\Db\Extension;
}
```

#### upsert(string $table, array $data, array $criteria): bool

[](#upsertstring-table-array-data-array-criteria-bool)

Insert or update data row in given table as per given criteria.

```
$di->get('db')->upsert('users', ['name' => 'John'], ['username' => 'johnny']);
```

#### insertAsBulk(string $table, array $data): bool

[](#insertasbulkstring-table-array-data-bool)

Insert many items at once - in one query - no loop.

```
$di->get('db')->insertAsBulk('table', [
    ['name' => 'name1', 'status' => 'status1'],
    ['details' => 'detail2', 'name' => 'name2'], // columns dont need to be ordered or balanced
]);
```

#### countBy(string $table, array $criteria): int

[](#countbystring-table-array-criteria-int)

Count rows in table by criteria.

```
$di->get('db')->countBy('table', ['name' => 'name1', 'status' => 'ok']);
```

### Db.Logger

[](#dblogger)

Hook into the db as an event listener and log all the sql queries- binds are interpolated.

```
$di->setShared('config', new \Phalcon\Config([
    'sqllogger' => [
        'enabled'        => true,
        'logPath'        => __DIR__ . '/.var/sql/', // directory
        'addHeader'      => true,
        'backtraceLevel' => 5,
        'skipFirst'      => 2,
    ],
]);

$di->get('db')->registerLogger($di->get('config')->toArray()['sqllogger']);
```

---

### Di.Extension

[](#diextension)

**Foreword** This whole example and the entire `phalcon-ext` package almost always used `$di->get('service')` and not `$di->getShared('service')`, this is because if you have set 'service' as shared, `get()` will return that same shared instance again and again and if not then it will spawn new instance- the point is if we dont want new instance why dont we `setShared()` it? One has to consciously think whether to `setShared()` or `set()` instead of `getShared()` or `get()`.

#### Setup

[](#setup-3)

```
$di = new \PhalconExt\Di\FactoryDefault;

// Or if you have your own already, just use the trait
class YourDi extends \Phalcon\Di
{
    use PhalconExt\Di\Extension;
}
```

#### registerAliases(array $aliases): self

[](#registeraliasesarray-aliases-self)

Register aliases for di service so they can be resolved automatically by name &amp;/or typehints.

```
$di->registerAliases([
    'TheAlias'                 => 'service',
    \Phalcon\Db\Adapter::class => 'db',
]);
```

#### resolve(string $class, array $parameters = \[\]): mixed

[](#resolvestring-class-array-parameters---mixed)

Recursively resolve all dependencies of a given class FQCN and return new instance.

```
$instance = $di->resolve(\Some\Complex\ClassName::class, $parameters);
```

#### replace(array $services): self

[](#replacearray-services-self)

Override a di service but keep backup so it may be restored if needed (great for tests)

```
$di->replace(['service' => new \MockedService]);
```

#### restore(?string $service)

[](#restorestring-service)

Restore the overridden services to their usual defaults.

```
$di->restore();          // All
$di->restore(['service']); // One
```

### Di.ProvidesDi

[](#diprovidesdi)

#### di(?string $service): mixed

[](#distring-service-mixed)

Easily resolve di services with this shortcut.

```
class AnyClass
{
    use \PhalconExt\Di\ProviesDi;

    public function anyFn()
    {
        $di = $this->di();
        $db = $this->di('db');
    }
}
```

---

### Http.BaseMiddleware

[](#httpbasemiddleware)

A base implementation for middlewares on top of which you can create your own middlewares. You just have to implement one or both of `before()` &amp;/or `after()` methods that recieves `request` and `response` objects. See an example for Ajax middleware:

```
$di->setShared('config', new \Phalcon\Config([
    'ajax' => [
        'uriPrefix' => '/ajax',
    ],
]);

class Ajax extends \PhalconExt\Http\BaseMiddleware
{
    /** @var string The root key in config having settings for Ajax middleware */
    protected $configKey = 'ajax';

    /**
     * For any uri starting with `/ajax`, allow if only it is real ajax request.
     *
     * Register as before handler because we will abort before actual exceution if not ajax.
     *
     * @return bool
     */
    public function before(Phalcon\Http\Request $request, Phalcon\Http\Response $response): bool
    {
        list(, $uri) = $this->getRouteNameUri();

        if (\stripos($uri, $this->config['uriPrefix']) !== 0) {
            return true;
        }

        if (!$request->isAjax()) {
            // Aborts/stops the app. All other middlewares down the line are skipped
            return $this->abort(400);
        }

        return true;
    }
}

// Usage is pretty simple:
// Create an app!
$app = new Phalcon\Mvc\Application($di);
// OR micro
$app = new Phalcon\Mvc\Micro($di);

// Wrap the app with middleware and run it
(new PhalconExt\Http\Middlewares([Ajax::class]))->wrap($app);
```

#### Http.Middleware.ApiAuth

[](#httpmiddlewareapiauth)

JWT based api authentication middleware that intercepts `POST /api/auth` request and generates or refreshes `access_token` based on `grant_type`. For all other requests it checks `Authorization: Bearer ` and only allows if that is valid and the scopes are met. You can configure scopes on per endpoint basis. You can access currently authenticated user through out the app using:

```
$di->get('authenticator')->getSubject();
```

#### Setup

[](#setup-4)

```
$di->setShared('config', new \Phalcon\Config([
    'apiAuth' => [
        // 14 days in seconds (http://stackoverflow.com/questions/15564486/why-do-refresh-tokens-expire-after-14-days)
        'refreshMaxAge'  => 1209600,
        // Prefix to use in stored tokens (max 4 chars)
        'tokenPrefix'    => 'RF/',
        // The route to generate/refresh access tokens.
        // genrerate: curl -XPOST -d 'grant_type=password&username=&password=' /api/auth
        // refresh:   curl -XPOST -d 'grant_type=refresh_token&refresh_token=' /api/auth
        // It can also accept json payload:
        //   -H 'content-type: application/json' -d {"grant_type":"refresh_token","refresh_token":""}
        'authUri' => '/api/auth',

        // The permission scopes required for a route
        'scopes' => [
            '/some/uri' => 'admin',
            '/next/uri' => 'user',
        ],

        // Json Web tokens configuration.
        'jwt'            => [
            'keys'       => [
                // kid => key (first one is default always)
                'default' => '*((**@$#@@KJJNN!!#D^G&(U)KOIHIYGTFD',
            ],
            'algo'       => 'HS256',
            // 15 minutes in seconds.
            'maxAge'     => 900,
            // Grace time in seconds.
            'leeway'     => 10,
            // Only for RS algo.
            'passphrase' => '',
            // Name of the app/project.
            'issuer'     => '',
        ],
    ],
]);

// Usage:
(new PhalconExt\Http\Middlewares([
    PhalconExt\Http\Middleware\ApiAuth::class,
]))->wrap(new Phalcon\Mvc\Micro($di));
```

#### Http.Middleware.Cache

[](#httpmiddlewarecache)

Caches output for requests to boost performance heavily. Requires redis service. Currently by design only GET requests are cached and this might change.

#### Setup

[](#setup-5)

```
$di->setShared('config', new \Phalcon\Config([
    'httpCache' => [
        // cache life- time to live in mintues
        'ttl'       => 60,
        // White listed uri/routes to enable caching
        'routes'    => [
            // for absolute uri, prepend forward `/`
            '/content/about-us',
            // or you can use route name without a `/`
            'home',
        ],
    ],
]);
```

#### Http.Middleware.Cors

[](#httpmiddlewarecors)

Enables cors with preflight for configured origins and request options.

#### Setup

[](#setup-6)

```
$di->setShared('config', new \Phalcon\Config([
    'cors' => [
        'exposedHeaders' => [],
        // Should be in lowercases.
        'allowedHeaders' => ['x-requested-with', 'content-type', 'authorization'],
        // Should be in uppercase.
        'allowedMethods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
        // Requests originating from here can entertain CORS.
        'allowedOrigins' => [
            'http://127.0.0.1:1234',
        ],
        // Cache preflight for 7 days (expressed in seconds).
        'maxAge'         => 604800,
    ],
]);
```

#### Http.Middleware.Throttle

[](#httpmiddlewarethrottle)

Throttles the flooded requests as per time and quota of your choosing. Requires redis service.

#### Setup

[](#setup-7)

```
$di->setShared('config', new \Phalcon\Config([
    'throttle' => [
        'maxHits' => [
            // Mintues => Max Hits
            1    => 10,
            60   => 250,
            1440 => 4500,
        ],
        'checkUserAgent' => false,
        // Cache key prefix
        'prefix'         => '_',
    ],
]);
```

#### Usage

[](#usage)

Middlewares can be used as a wrapper to app using `PhalconExt\Http\Middlewares` manager.

```
$app = new Phalcon\Mvc\Micro($di);

// Set all your middlewares in an array using class FQCN, they are lazily loaded
// They are executed in order of their presence
// If a middleware returns `false` from its `before()` or `after()` events,
// all other middlewares down the line are skipped
$middlewares = new PhalconExt\Http\Middlewares([
    PhalconExt\Http\Middleware\Throttle::class,
    PhalconExt\Http\Middleware\ApiAuth::class,
    PhalconExt\Http\Middleware\Cors::class,
    PhalconExt\Http\Middleware\Cache::class,
]);

// Wrap and run the app!
$middlewares->wrap($app);

// The app is wrapped and run automatically so you dont have to do:
// $app->handle();
```

---

### Logger.EchoLogger

[](#loggerechologger)

#### log(string $message, int $type, array $context = \[\])

[](#logstring-message-int-type-array-context--)

Echoes anything right away - but you can control formatting and log level.

```
$echo = $this->di(\PhalconExt\Logger\EchoLogger::class, ['config' => ['level' => Logger::INFO]]);
$echo->log('Message {a}', \Phalcon\Logger::INFO, ['a' => 'ok']);
```

### Logger.LogsToFile

[](#loggerlogstofile)

#### log(string $message, int $type, array $context = \[\])

[](#logstring-message-int-type-array-context---1)

Delegate mundane file logging task to this trait thereby cutting down boilerplate codes.

```
class AnyClass
{
    use \PhalconExt\Logger\LogsToFile;

    protected $fileExtension = '.log';

    public function anyFn()
    {
        $this->activate('/path/to/log/dir/');

        $this->log('Some message', \Phalcon\Logger::INFO);
    }
}
```

---

### Mail.Mailer

[](#mailmailer)

A Phalcon adapter/bridge/container/delegator (read: abcd) to swiftmailer.

#### Setup

[](#setup-8)

```
$di->setShared('config', new \Phalcon\Config([
    'mail' => [
        'driver' => 'null',
        'from'   => [
            'name'  => 'Test',
            'email' => 'test@localhost',
        ],

        // for driver 'smtp':
        'host'       => 'smtp.server.com',
        'port'       => 425,
        'encryption' => true,
        'username'   => 'user',
        'password'   => 'pass',

        // for driver sendmail only (optional)
        'sendmail' => '/sendmail/binary',
    ],
]);

$di->setShared('mailer', function () {
    return new \PhalconExt\Mail\Mailer($this->get('config')->toArray()['mail']);
});
```

### Mail.Mail

[](#mailmail)

A child of swiftmail message to allow attaching attachments without much ado.

```
$mail = $di->get('mailer')->newMail();
// Or from view template
$mail = $di->get('mailer')->newTemplateMail('view/file.twig', ['view' => 'params']);

$mail->setTo('test@localhost')->setSubject('Hi')->setBody('Hello')->mail();

// Attachments:
$mail->attachFile('/path/to/file', 'optional attachment name');

$mail->attachFiles(['/path/to/file1', '/path/to/file2']);
// OR
$mail->attachFiles([
    'attachment name 1' => '/path/to/file1',
    'attachment name 2' => '/path/to/file2',
]);

$mail->attachRaw('Raw plain text data', 'rawtext.txt', 'text/plain');
```

### Mail.Mailable

[](#mailmailable)

#### mail()

[](#mail)

Like Logger.LogsToFile above, but for mails.

```
class AnyClass
{
    use \PhalconExt\Mail\Mailable;

    public function anyFn()
    {
        $this->mail('test@local', 'Hi', ['body' => 'Hello']);
        $this->mail('test@local', 'Hi', ['template' => 'view/file.twig', 'params' => ['key' => 'value']]);
    }
}
```

### Mail.Logger

[](#maillogger)

Automatically logs all sent mails into file as a swiftmailer event listener- you can choose log formats: `eml | html | json`.

#### Setup

[](#setup-9)

```
$di->setShared('config', new \Phalcon\Config([
    'mail' => [
        'driver' => 'null',
        'from'   => [
            'name'  => 'Test',
            'email' => 'test@localhost',
        ],
        'logger' => [
            'enabled' => true,
            'logPath' => __DIR__ . '/.var/mail/', // directory
            'type'    => 'eml', // options: json, html, eml
        ],
    ],
]);

// When setting mailer, include config `mail>logger` and it is auto set up.
$di->setShared('mailer', function () {
    return new \PhalconExt\Mail\Mailer($this->get('config')->toArray()['mail']);
});
```

---

### Util.OpcachePrimer

[](#utilopcacheprimer)

#### prime(array $paths): int

[](#primearray-paths-int)

Ensures to warm up opcache for all files in given path well before file exceution. Opcache caches are specific to the sapi it is run. So for web, you need to have an endpoint

```
$primer = new \PhalconExt\Util\OpcachePrimer;

$total = $primer->prime(['/path/to/project/src', '/path/to/project/app/', '/path/to/project/vendor/']);
```

---

### Validation.Validation

[](#validationvalidation)

Validate data like we did in elsewhere- setting rules as .well-known strings or key=&gt;value pairs (array).

#### Setup

[](#setup-10)

```
$di->setShared('validation', \PhalconExt\Validation\Validation::class);
```

#### register(string $ruleName, $handler, string $message = ''): self

[](#registerstring-rulename-handler-string-message---self)

Register a new validation rule.

```
$di->get('validation')->register('gmail', function ($data) {
    // You can access current validation instance with `$this`
    // You can also access current validator options with `$this->getOption(...)`
    return stripos($this->getCurrentValue(), '@gmail.com') > 0;
}, 'Field :field must be an email with @gmail.com');
```

#### registerRules(array $ruleHandlers, array $messages = \[\]): self

[](#registerrulesarray-rulehandlers-array-messages---self)

Register many new validation rules at once.

```
$di->get('validation')->registerRules([
    'rule1' => function($data) { return true; },
    'rule1' => function($data) { return false; },
], [
    'rule1' => 'message1',
    'rule2' => 'message2'
]);
```

#### Usage

[](#usage-1)

```
$validation = $this->di('validation');

$rules = [
    // Can be string (With `abort` if the field `id` is invalid, following validations are aborted)
    'id'    => 'required|length:min:1;max:2;|in:domain:1,12,30|abort',
    // Can be an array too
    'email' => [
        'required' => true,
        'gmail'    => true,
        // With `abort` if the field `email` is invalid, following validations are aborted
        'abort'   => true,
    ],
    // validate if only exist in dataset
    'xyz' => 'length:5|if_exist',
];

// Validate against empty data (can be array or object)
$data = []; // OR $data = new \stdClas OR $data = new SomeClass($someData)
$validation->run($rules, $data);

$pass = $validation->pass(); // false
$fail = $validation->fail(); // true

$errors = $validation->getErrorMessages(); // array
```

#### Validation.Existence

[](#validationexistence)

Validates if something exists in database. You can optionally set table and column to check.

```
// Checks `users` table for `id` column with value 1
$rules = ['users' => 'exist'];
$data  = ['users' => 1]; // Data can be array

// Checks `users` table for `username` column with value 'admin'
$rules = ['username' => 'exist:table:users'];
$data  = new User(['username' => 'admin']); // Data can be model/entity

// Checks `users` table for `login` column with value 'admin@localhost'
$rules = ['email' => 'exist:table:users;column:login'];
$data  = (object) ['email' => 'admin@localhost']; // Data can be any Object

// Run the rules
$validation->run($rules, $data);
```

---

### View.Twig

[](#viewtwig)

Use twig view natively in Phalcon

#### Setup

[](#setup-11)

```
$di->setShared('config', new \Phalcon\Config([
    'view' => [
        'dir' => __DIR__ . '/view/',
    ],
    // Required
    'twig' => [
        'view_dirs'   => [__DIR__ . '/view/'], // array
        'auto_reload' => getenv('APP_ENV') !== 'prod',
        'cache'       => __DIR__ . '/.var/view/',
        // ... other options (see twig docs)
    ],
]);

// You must have view setup with twig engine enabled.
$di->setShared('view', function () {
    return (new View)
        ->setViewsDir($this->get('config')->toArray()['view']['dir'])
        ->registerEngines([
            '.twig' => 'twig',
        ]);
});

$di->setShared('twig', function () {
    $twig = new PhalconExt\View\Twig($this->get('view'), $this);

    // Here you can:
    // $twig->addFilter(...)
    // $twig->addExtension(...)

    return $twig;
});
```

#### Usage

[](#usage-2)

```
// standalone
$di->get('twig')->render('template.twig', ['view' => 'params']);
// or as view
$di->get('view')->render('template.twig', ['view' => 'params']); // .twig is optional
```

---

You can also see the [example](./example) codes for all these. Read [more](./example/readme.md).

### Related Projects

[](#related-projects)

- [adhocore/cli](https://github.com/adhocore/cli)
- [adhocore/jwt](https://github.com/adhocore/jwt)
- [adhocore/cron-expr](https://github.com/adhocore/cron-expr)

License
-------

[](#license)

> © 2017-2020, [Jitendra Adhikari](https://github.com/adhocore) | [MIT](./LICENSE)

### Credits

[](#credits)

This project is release managed by [please](https://github.com/adhocore/please).

###  Health Score

32

—

LowBetter than 69% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity28

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 98.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~56 days

Recently: every ~136 days

Total

11

Last Release

2374d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/2908547?v=4)[Jitendra Adhikari](/maintainers/adhocore)[@adhocore](https://github.com/adhocore)

---

Top Contributors

[![adhocore](https://avatars.githubusercontent.com/u/2908547?v=4)](https://github.com/adhocore "adhocore (375 commits)")[![dependabot-preview[bot]](https://avatars.githubusercontent.com/in/2141?v=4)](https://github.com/dependabot-preview[bot] "dependabot-preview[bot] (5 commits)")[![StyleCIBot](https://avatars.githubusercontent.com/u/11048387?v=4)](https://github.com/StyleCIBot "StyleCIBot (1 commits)")

---

Tags

adhocoreargv-parserconsole-applicationcorsloggermiddlewareoutputcachephalconphalcon-adaptersphalcon-extphalcon-jwtphp7swiftmailertask-schedulerthrottletwigvalidationphpmiddlewarevalidationtwigcorsdicacheloggerphalconswiftmailerphalcon-adaptersphalcon-extensionsrequest-throttleopcache-primerphalcon-argv-parserphalcon-tasksphalcon-cli

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/adhocore-phalcon-ext/health.svg)

```
[![Health](https://phpackages.com/badges/adhocore-phalcon-ext/health.svg)](https://phpackages.com/packages/adhocore-phalcon-ext)
```

###  Alternatives

[kevinrob/guzzle-cache-middleware

A HTTP/1.1 Cache for Guzzle 6. It's a simple Middleware to be added in the HandlerStack. (RFC 7234)

44018.6M133](/packages/kevinrob-guzzle-cache-middleware)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
