以 C 扩展编写的全功能栈PHP开发框架

其革命性的架构,使Phalcon成为有史以来最快的PHP开发框架!

开发人员不需要了解C语言就可以使用Phalcon。其功能在Phalcon命名空间下作为PHP类和接口公开,随时可以使用。
功能
  • 低开销
  • ORM
  • PHQL
  • 事务
  • 缓存
  • 视图 & 前端
  • 模板引擎
  • 模板引擎 (Volt)
  • i18n(国际化)
  • 表单生成器
  • 即时消息
赞助商

  • 低开销
    与传统框架相比,内存消耗和CPU低
  • MVC & HMVC
    模块,组件,模型,视图和控制器
  • 依赖注入
    依赖项注入和服务定位,它本身就是它们的容器.
  • Rest
    在这种情况下,您可以使用微型或全栈应用来达到您的目标。此外,还提供了一组功能强大的 HTTP 帮助器.
  • 自动加载器
    提供遵循PSR-4的PHP类的自动加载机制。
  • 路由
    Phalcon\Mvc\Router 提供高级路由功能.
Low overhead
PHP C-extension (Phalcon)
  • Zephir/C extensions are loaded together with PHP one time on the web server's daemon start process
  • Classes and functions provided by the extension are ready to use for any application
  • The code is compiled and isn't interpreted because it's already compiled to a specific platform and processor
  • Thanks to its low-level architecture and optimizations Phalcon provides the lowest overhead for MVC-based applications
MVC
Build single and multi-module applications with ease and pleasure. Using the file structure, scheme and patterns you already know.
                        
single/
    app/
        controllers/
        models/
        views/
    public/
        css/
        img/
        js/

                        
                    
                        
multiple/
     apps/
       frontend/
          controllers/
          models/
          views/
          Module.php
       backend/
          controllers/
          models/
          views/
          Module.php
       public/
       ../
                        
                    
Dependency Injection
Phalcon is built upon a powerful yet easy to understand and use pattern called Dependency Injection. Initialize or define services once - and use them virtually anywhere throughout the application.
                        
// Create the Dependency Injector Container
$di = new Phalcon\DI();

// Register classes, functions, components
$di->set("request", new Phalcon\Http\Request());

..

// Use anywhere else in code
$request = $di->getShared('request');
                        
                    
Restful Services
Writing REST servers and applications has never been easier. No boilerplate. Simple services will fit in one file.
                        
use Phalcon\Mvc\Micro;

$app = new Micro();

// Returning data in JSON
$app->get(
    '/check/status',
    function () {
        return $this
            ->response
            ->setJsonContent(
                [
                    'status' => 'important',
                ]
            )
        ;
    }
);

$app->handle();
                        
                    
Autoloader
Register namespaces, prefixes, directories or classes. Take advantage of the autoloader events and maintain full control over what files are loaded and from where.
                        
use Phalcon\Loader;

// Creates the autoloader
$loader = new Loader();

// Register some namespaces
$loader->registerNamespaces(
    [
       'Example\Base'    => 'vendor/example/base/',
       'Example\Adapter' => 'vendor/example/adapter/',
       'Example'         => 'vendor/example/',
    ]
);

// Register autoloader
$loader->register();
                        
                    
Router
Routing as it supposed to be. Nothing more. Nothing less.
                        
// Create the router
$router = new \Phalcon\Mvc\Router();

// Define a route
$router->add(
   '/admin/users/my-profile',
   [
       'controller' => 'users',
       'action'     => 'profile',
   ]
);
                        
                    
  • ORM
    对象关系映射
  • PHQL
    强大且安全的Phalcon查询语言PHQL
  • 事务
    Phalcon中的事务可确保数据完整性安全。
  • 缓存
    利用Phalcon提供的许多后端缓存来提高性能
ORM
A powerful ORM is provided by Phalcon allowing you to manipulate database records as classes and objects. MySQL, PostgreSQL and SQLite are supported out of the box.
                        
use Invoices;
use Phalcon\Mvc\Model;

class Customers extends Model
{
    public $cst_id;

    public $cst_name;

    public function initialize()
    {
        $this->hasMany(
            'cst_id',
            Invoices::class,
            'inv_cst_id'
        );
    }
}
                        
                    
PHQL
PHQL is a high-level, object-oriented SQL dialect that allows to write queries using a standardized SQL-like language. PHQL is implemented as a parser (written in C) that translates syntax in that of the target RDBMS. To achieve the highest performance possible, Phalcon provides a parser that uses the same technology as SQLite. This technology provides a small in-memory parser with a very low memory footprint that is also thread-safe.
                        
$phql  = 'SELECT * '
       . 'FROM Formula\Cars '
       . 'ORDER BY Formula\Cars.name';
$query = $manager->createQuery($phql);

$phql  = 'SELECT Formula\Cars.name '
       . 'FROM Formula\Cars '
       . 'ORDER BY Formula\Cars.name';
$query = $manager->createQuery($phql);

$phql  = 'SELECT c.name '
       . 'FROM Formula\Cars c '
       . 'ORDER BY c.name';
$query = $manager->createQuery($phql);

$phql = 'SELECT c.* '
      . 'FROM Cars AS c '
      . 'ORDER BY c.name';
$cars = $manager->executeQuery($phql);

foreach ($cars as $car) {
    echo "Name: ", $car->name, "\n";
}
                        
                    
Transactions
When a process performs multiple database operations, it might be important that each step is completed successfully so that data integrity can be maintained. Transactions offer the ability to ensure that all database operations have been executed successfully before the data is committed to the database.
                        
use Phalcon\Mvc\Model\Transaction\Failed;
use Phalcon\Mvc\Model\Transaction\Manager;

try {

    // Create a transaction manager
    $manager = new Manager();

    // Request a transaction
    $transaction = $manager->get();

    // Get the robots to be deleted
    $invoices = Invoices::find(
        'inv_cst_id = 123'
    );

    foreach ($invoices as $invoice) {
        $invoice->setTransaction($transaction);
        if ($invoice->delete() == false) {
            // Something is wrong - rollback transaction
            foreach ($invoice->getMessages() as $message) {
                $transaction
                    ->rollback($message->getMessage());
            }
        }
    }

    // Everything is OK - commit transaction
    $transaction->commit();

    echo "Robots were deleted successfully!";

} catch (Failed $e) {
    echo "Failed, reason:  ", $e->getMessage();
}
                        
                    
Cache
The cache component allows faster access to frequently used or already processed data. It supports many backends such as Redis, Memcached, Mongo, Files, Apc and more
                        
use Phalcon\Cache;
use Phalcon\Cache\AdapterFactory;
use Phalcon\Storage\Serializer\SerializerFactory;

$serializerFactory = new SerializerFactory();
$adapterFactory    = new AdapterFactory($serializerFactory);

$options = [
    'defaultSerializer' => 'Json',
    'lifetime'          => 7200
];

$adapter = $adapterFactory
    ->newInstance('apcu', $options);

$cache = new Cache($adapter);
                        
                    
  • 模板引擎
    视图代表应用程序的用户界面
  • 模板引擎 (Volt)
    受Jinja启发但以 C 为 PHP 构建的模板引擎
  • i18n(国际化)
    轻松将您的应用程序翻译成多种语言
  • 表单生成器
    轻松创建HTML表单
  • 即时消息
    即时消息用于通知用户有关操作状态的信息。
Template Engines
Views represent the user interface of your application. Views are often HTML files with embedded PHP code that perform tasks related solely to the presentation of the data. Views handle the job of providing data to the web browser or other tool that is used to make requests from your application.
                        
<html>
    <body>
    <div class='top'>
        <?php $this->partial('shared/ad_banner'); ?>
    </div>
    <div class='content'>
        <h1>Robots</h1>
        <p>
            Check out our specials for robots:
        </p>
        ...
    </div>
    <div class='footer'>
        <?php $this->partial('shared/footer'); ?>
    </div>
    </body>
</html>
                        
                    
Template Engine (Volt)
Volt is an ultra-fast and designer friendly templating language written in Zephir/C for PHP. It provides you a set of helpers to write views in an easy way. Volt is highly integrated with other components of Phalcon, just as you can use it as a stand-alone component in your applications.
                        
{# app/views/products/show.volt #}
{% block last_products %}
{% for prod in products %}
    * Name: {{ prod.name|e }}
    {% if prod.status == 'Active' %}
       Price: {{ prod.price + prod.taxes/100}}
    {% endif  %}
{% endfor  %}
{% endblock %}
                        
                    
i18n
The component Phalcon\Translate aids in creating multilingual applications. Applications using this component, display content in different languages, based on the user's chosen language supported by the application.
// app/messages/en.php
$messages = [
    'hi'      => 'Hello',
    'bye'     => 'Good Bye',
    'hi-name' => 'Hello %name%',
    'song'    => 'This song is %song%'
];

// app/messages/es.php
$messages = [
    'hi'      => 'Hola',
    'bye'     => 'Adiós',
    'hi-name' => 'Hola %name%',
    'song'    => 'Esta canción es %song%'
];

use Phalcon\Mvc\Controller;
use Phalcon\Translate\Adapter\NativeArray;

// UserController.php
class UserController extends Controller
{
    protected function getTranslation()
    {
        // Browser's best language
        $language = $this
            ->request
            ->getBestLanguage();

        // Check the lang translation file
        $fileName = 'app/messages/'
                  . $language
                  . '.php';
        if (file_exists($fileName) {
            require $fileName;
        } else {
            // Fallback to some default
            require 'app/messages/en.php';
        }

        // Return a translation object
        return new NativeArray(
            array(
                'content' => $messages
            )
        );
    }

    public function indexAction()
    {
        $this->view->name = 'Mike';

        $this->view->t = $this
            ->getTranslation();
    }
}
// user.volt
<p><?php echo $t->_('hi'), ' ', $name; ?></p>
                        
                    
Forms Builder
Each element in the form can be rendered as required by the developer. Internally, Phalcon\Tag is used to produce the correct HTML for each element and you can pass additional HTML attributes as the second parameter of render():
                        
use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\Select;

$form = new Form();

$form->add(new Text('name'));

$form->add(new Text('telephone'));

$form->add(
    new Select(
        'telephoneType',
        array(
            'H' => 'Home',
            'C' => 'Cellphone'
        )
    )
);
                        
                    
Flash messages
Use the flash notifier to show notifications to a user in a web application:
                        
use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function saveAction()
    {
        $this->flash->error(
            'there were errors in this form'
        );
        $this->flash->success(
            'yes!, everything is fine'
        );
        $this->flash->notice(
            'this is a notice for users'
        );
        $this->flash->warning(
            'this is just a warning'
        );
    }
}
                        
                    
  • ACL
    访问控制列表允许用户访问他们有权访问的模块
  • Sharding(分片)
    同时连接,存储和检索来自多个数据库系统的数据
  • 加密
    加密/解密重要数据,使其免受未经授权的第三方的攻击
  • 事件
    通过设置"挂钩点"来扩展大部分框架组件。创建您自己的事件,使您的应用程序更加灵活和强大
ACL
This is how you can built the access control list (ACL):
                        
use Phalcon\Acl;
use Phalcon\Acl\Enum;
use Phalcon\Acl\Role;
use Phalcon\Acl\Adapter\Memory;

// Create the ACL
$acl = new Memory();

// The default action is DENY access
$acl->setDefaultAction(Enum::DENY);

// Register two roles, Users
// and Guests
$roles = array(
    'users'  => new Role('Users'),
    'guests' => new Role('Guests')
);

foreach ($roles as $role) {
    $acl->addRole($role);
}
                        
                    
Sharding
Attach models to different databases
                        
use Phalcon\Db\Adapter\Pdo\Mysql;
use Phalcon\Db\Adapter\Pdo\PostgreSQL;

// This service returns a MySQL database
$container->set(
    'dbMysql',
    function () {
        return new Mysql(
            [
                'host'     => 'localhost',
                'username' => 'root',
                'password' => 'secret',
                'dbname'   => 'tutorial',
            ]
        );
    }
);

// This service returns a PostgreSQL database
$container->set(
    'dbPostgres',
    function () {
        return new PostgreSQL(
            [
                'host'     => 'localhost',
                'username' => 'postgres',
                'password' => '',
                'dbname'   => 'invo',
            ]
        );
    }
);
                        
                    
Encryption
Phalcon provides encryption facilities via the Phalcon\Crypt component. This class offers simple object-oriented wrappers to the openssl PHP's encryption library.
                        
use Phalcon\Crypt;

$crypt = new Crypt();

$key  = 'This is a secret key (32 bytes).';
$text = 'The text you want to encrypt.';

$encrypted = $crypt->encrypt($text, $key);

echo $crypt->decrypt($encrypted, $key);
                        
                    
Events Management
An EventsManager allows us to attach listeners to a particular type of event. The type that interests us now is 'dispatch'. The following code filters all events produced by the Dispatcher:
                        
use Phalcon\Mvc\Dispatcher;
use Phalcon\Events\Manager;

$container->set(
    'dispatcher',
    function () {
        // Create an events manager
        $manager = new Manager();

        // Listen for events produced in the
        // dispatcher using the SecurityPlugin
        $manager->attach(
            'dispatch:beforeExecuteRoute',
            new SecurityPlugin
        );

        // Handle exceptions and not-found
        // exceptions using NotFoundPlugin
        $manager->attach(
            'dispatch:beforeException',
            new NotFoundPlugin
        );

        $dispatcher = new Dispatcher();

        // Assign the events manager
        // to the dispatcher
        $dispatcher
            ->setEventsManager($manager);

        return $dispatcher;
    }
);
                        
                    
在15分钟时间内从头开始构建投票程序
观看演示视频
快来加入我们充满活力的开发者社区!
Community contributions in Extensions, Plugins, Adapters, VM, examples, source code... and more