Hướng dẫn config Cakephp 4

  • August 8, 2022
  • 808

Các file config của cakephp được chứa trong thư mục config. Đây là nơi chứa các config của cakephp. Nếu bạn muốn thêm config riêng cho dựa án của mình cũng có thể thêm các file config của mình trong thư mục config. Các file config sẽ được load trong file config/bootstrap.php

Giờ chúng ta cùng tìm hiểu các cấu hình trong cakephp nhé.

Load new config with cakephp


// Tạo 1 file config các thông tin của config của firebase trong thư mục config
// File name config/firebase.php 
return [
    'Firebase' => [
        'push_url' => 'https://fcm.googleapis.com/fcm/send',
        'create_dynamic_link_url' => 'https://firebasedynamiclinks.googleapis.com/v1/shortLinks',
        'server_key' => env('FIREBASE_SERVER_KEY'),
        'api_key' => env('FIREBASE_API_KEY'),
        'bundle_id' => env('FIREBASE_BUNDLE_ID'),
        ]
];

// Load file config in file config/bootstrap.php
Configure::load('firebase', 'default');

// Get config from firebase config file
$firebaseServerKey = Configure::read('Firebase.server_key');

Environment Variables

Các biến môi trường trong cakephp được khai báo trong file config/.env, mặc định cakephp tạo sẵn file config/.env.example khi cài đặt app cần phải tạo file .env được copy từ file .env.example. Chúng ta cũng có thể tạo thêm các file .env.dev, .env.staging, .env.production để khai báo cái biến cho từng môi trường. Vậy làm thế nào để dùng được biết môi trường? Chúng ta cần làm các bước sau:


// Install packagist josegonzalez/dotenv với composer
composer install josegonzalez/dotenv:^3.2

// Enable paser config from file .env trong file config/bootstrap.php
if (!env('APP_NAME') && file_exists(CONFIG . '.env')) {
    $dotenv = new \josegonzalez\Dotenv\Loader([CONFIG . '.env']);
    $dotenv->parse()
        ->putenv()
        ->toEnv()
        ->toServer();
}

// Lấy giá trị biến env bằng hàm env()
$debug = env('APP_DEBUG', false);
// Trả về giá trị của biến APP_DEBUG trong file .env
// Nếu APP_DEBUG được không khai báo thì lấy giá trị mặc định là false

General Configuration

Các config cơ bản của cakephp được lưu trong file config/app.php và file config/app_local.php, các config trong file app_local.ph có thể ghi đè giá trị trong file config/app.php

Tìm hiểu 1 số config quan trọng trong file config/app.php

debug

có 2 level debug, nếu debug = false dùng cho môi trường prod, các log lỗi không hiển thị cho người dùng biết, debug = true dùng cho môi trường develop, hiển thị các lỗi, cho dev dễ dàng check lỗi.

App.encoding

Define encoding cho app

App.defaultLocale

thiết lập ngôn ngữ mặc định cho ứng dụng

App.defaultTimezone

Thiết lập thời gian mặc định

Security.salt

Mã bảo mật của cakephp, nếu app dùng trên nhiều server cần config dùng chung 1 security salt

Cache

Thiết lập cache


 /*
     * Configure the cache adapters.
     */
    'Cache' => [
        'default' => [
            'className' => FileEngine::class,
            'path' => CACHE,
            'url' => env('CACHE_DEFAULT_URL', null),
        ],

        /*
         * Configure the cache used for general framework caching.
         * Translation cache files are stored with this configuration.
         * Duration will be set to '+2 minutes' in bootstrap.php when debug = true
         * If you set 'className' => 'Null' core cache will be disabled.
         */
        '_cake_core_' => [
            'className' => FileEngine::class,
            'prefix' => 'myapp_cake_core_',
            'path' => CACHE . 'persistent' . DS,
            'serialize' => true,
            'duration' => '+1 years',
            'url' => env('CACHE_CAKECORE_URL', null),
        ],

        /*
         * Configure the cache for model and datasource caches. This cache
         * configuration is used to store schema descriptions, and table listings
         * in connections.
         * Duration will be set to '+2 minutes' in bootstrap.php when debug = true
         */
        '_cake_model_' => [
            'className' => FileEngine::class,
            'prefix' => 'myapp_cake_model_',
            'path' => CACHE . 'models' . DS,
            'serialize' => true,
            'duration' => '+1 years',
            'url' => env('CACHE_CAKEMODEL_URL', null),
        ],

        /*
         * Configure the cache for routes. The cached routes collection is built the
         * first time the routes are processed through `config/routes.php`.
         * Duration will be set to '+2 seconds' in bootstrap.php when debug = true
         */
        '_cake_routes_' => [
            'className' => FileEngine::class,
            'prefix' => 'myapp_cake_routes_',
            'path' => CACHE,
            'serialize' => true,
            'duration' => '+1 years',
            'url' => env('CACHE_CAKEROUTES_URL', null),
        ],
    ],

Database

config database trong file app_local.php


/*
     * Connection information used by the ORM to connect
     * to your application's datastores.
     *
     * See app.php for more configuration options.
     */
    'Datasources' => [
        'default' => [
            'host' => 'myapp-mysql',
            /*
             * CakePHP will use the default DB port based on the driver selected
             * MySQL on MAMP uses port 8889, MAMP users will want to uncomment
             * the following line and set the port accordingly
             */
            //'port' => 'non_standard_port_number',

            'username' => 'myapp',
            'password' => 'myapp',

            'database' => 'myapp',
            /*
             * If not using the default 'public' schema with the PostgreSQL driver
             * set it here.
             */
            //'schema' => 'myapp',

            /*
             * You can use a DSN string to set the entire configuration
             */
            'url' => env('DATABASE_URL', null),
        ],

        /*
         * The test connection is used during the test suite.
         */
        'test' => [
            'host' => 'localhost',
            //'port' => 'non_standard_port_number',
            'username' => 'my_app',
            'password' => 'secret',
            'database' => 'test_myapp',
            //'schema' => 'myapp',
            'url' => env('DATABASE_TEST_URL', 'sqlite://127.0.0.1/tests.sqlite'),
        ],
    ],

Email


/*
     * Email configuration.
     *
     * By defining transports separately from delivery profiles you can easily
     * re-use transport configuration across multiple profiles.
     *
     * You can specify multiple configurations for production, development and
     * testing.
     *
     * Each transport needs a `className`. Valid options are as follows:
     *
     *  Mail   - Send using PHP mail function
     *  Smtp   - Send using SMTP
     *  Debug  - Do not send the email, just return the result
     *
     * You can add custom transports (or override existing transports) by adding the
     * appropriate file to src/Mailer/Transport. Transports should be named
     * 'YourTransport.php', where 'Your' is the name of the transport.
     */
    'EmailTransport' => [
        'smtp' => [
            'host' => env('MAIL_HOST', 'smtp.mailtrap.io'),
            'port' => env('MAIL_PORT', 2525),
            'username' => env('MAIL_USERNAME'),
            'password' => env('MAIL_PASSWORD'),
            'className' => SmtpTransport::class,
            'tls' => true
        ],
        'ses' => [
            'className' => AwsSesTransport::class,
            'region' => env('MAIL_REGION', 'us-east-1'),
            'version' => 'latest',
            'aws_access_key_id' => env('MAIL_ACCESS_KEY_ID'),
            'aws_access_secret_key' => env('MAIL_ACCESS_SECRET_KEY'),
            'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
        ],
        'Debug' => [
            'className' => 'Debug'
        ],
    ],

    /*
     * Email delivery profiles
     *
     * Delivery profiles allow you to predefine various properties about email
     * messages from your application and give the settings a name. This saves
     * duplication across your application and makes maintenance and development
     * easier. Each profile accepts a number of keys. See `Cake\Mailer\Email`
     * for more information.
     */
    'Email' => [
        'default' => [
            'transport' => env('MAIL_MAILER', 'ses'),
            'from' => env('MAIL_FROM_ADDRESS'),
            /*
             * Will by default be set to config value of App.encoding, if that exists otherwise to UTF-8.
             */
            'charset' => 'utf-8',
            'headerCharset' => 'utf-8',
            'url' => env('EMAIL_DEFAULT_URL', null)
        ],
    ],

Error and handle exception

Thiết lập error log và handle exception, có thể thiết lập level log, bỏ qua log lỗi và handle exception


'Error' => [
        'errorLevel' => E_ALL,
        'skipLog' => [],
        'log' => true,
        'trace' => true,
        'ignoredDeprecationPaths' => [],
    ],

Tóm lại các config của cakephp sẽ được thiết lập trong thư mục config Khi cần thay đổi các thông tin config chúng ta sẽ sửa ở file .env config/app.php config/app_local.php