CakePHP 프로젝트 구성

WBOY
풀어 주다: 2024-09-10 17:25:03
원래의
258명이 탐색했습니다.

이 장에서는 CakePHP의 환경 변수, 일반 구성, 데이터베이스 구성이메일 구성에 대해 알아 보겠습니다.

구성 CakePHP에는 기본적으로 하나의 구성 파일이 제공되며 필요에 따라 수정할 수 있습니다. 이 목적을 위한 전용 폴더 “config”가 하나 있습니다. CakePHP에는 다양한 구성 옵션이 제공됩니다.

CakePHP의 환경변수부터 알아보겠습니다.

환경변수

환경 변수를 사용하면 다양한 환경에서 애플리케이션을 쉽게 작동할 수 있습니다. 예를 들어 개발 서버, 테스트 서버, 스테이징 서버 및 프로덕션 서버 환경입니다. 이러한 모든 환경에 대해 env() 함수를 사용하여 필요한 환경에 대한 구성을 읽고 애플리케이션을 구축할 수 있습니다.

config 폴더에 config/.env.example이 있습니다. 이 파일에는 환경에 따라 변경되는 모든 변수가 있습니다. 우선 config 폴더(예: config/.env)에 파일을 만들고 해당 변수를 정의하여 사용할 수 있습니다. 추가 변수가 필요한 경우 해당 파일에 넣을 수 있습니다.

아래와 같이 env() 함수를 사용하여 환경 변수를 읽을 수 있습니다. −

$debug = env('APP_DEBUG', false);
로그인 후 복사

첫 번째는 원하는 환경 변수 이름이고 두 번째 값은 기본값입니다. 환경변수에 값이 없으면 기본값이 사용됩니다.

일반 구성

다음 표에서는 다양한 변수의 역할과 이러한 변수가 CakePHP 애플리케이션에 미치는 영향을 설명합니다.

선생님 번호 변수 이름 및 설명
1
Sr.No Variable Name & Description
1

debug

Changes CakePHP debugging output.

false = Production mode. No error messages, errors, or warnings shown.

true = Errors and warnings shown.

2

App.namespace

The namespace to find app classes under.

3

App.baseUrl

Un-comment this definition, if you don’t plan to use Apache’s mod_rewrite with CakePHP. Don’t forget to remove your .htaccess files too.

4

App.base

The base directory the app resides in. If false, this will be auto detected.

5

App.encoding

Define what encoding your application uses. This encoding is used to generate the charset in the layout, and encode entities. It should match the encoding values specified for your database.

6

App.webroot

The webroot directory.

7

App.wwwRoot

The file path to webroot.

8

App.fullBaseUrl

The fully qualified domain name (including protocol) to your application’s root.

9

App.imageBaseUrl

Web path to the public images directory under webroot.

10

App.cssBaseUrl

Web path to the public css directory under webroot.

11

App.jsBaseUrl

Web path to the public js directory under webroot.

12

App.paths

Configure paths for non-class based resources. Supports the plugins, templates, locales, subkeys, which allow the definition of paths for plugins, view templates and locale files respectively.

13

Security.salt

A random string used in hashing. This value is also used as the HMAC salt when doing symmetric encryption.

14

Asset.timestamp

Appends a timestamp, which is last modified time of the particular file at the end of asset files URLs (CSS, JavaScript, Image) when using proper helpers. The valid values are −

  • (bool) false - Doesn’t do anything (default).

  • (bool) true - Appends the timestamp, when debug is true.

  • (string) ‘force’ - Always appends the timestamp.

디버그 CakePHP 디버깅 출력을 변경합니다. 거짓 = 생산 모드. 오류 메시지, 오류 또는 경고가 표시되지 않습니다. true = 오류 및 경고가 표시됩니다.
2 App.namespace 앱 클래스를 찾는 네임스페이스입니다.
3 App.baseUrl CakePHP에서 Apache의 mod_rewrite를 사용할 계획이 없다면 이 정의의 주석을 해제하세요. .htaccess 파일도 제거하는 것을 잊지 마세요.
4 App.base 앱이 상주하는 기본 디렉터리입니다. false인 경우 자동으로 감지됩니다.
5 App.encoding 애플리케이션에서 사용하는 인코딩을 정의하세요. 이 인코딩은 레이아웃에서 문자 세트를 생성하고 엔터티를 인코딩하는 데 사용됩니다. 데이터베이스에 지정된 인코딩 값과 일치해야 합니다.
6 App.webroot 웹루트 디렉터리.
7 App.wwwRoot 웹루트 파일 경로입니다.
8 App.fullBaseUrl 애플리케이션 루트에 대한 정규화된 도메인 이름(프로토콜 포함).
9 App.imageBaseUrl webroot 아래의 공개 이미지 디렉토리에 대한 웹 경로입니다.
10 App.cssBaseUrl webroot 아래의 공개 CSS 디렉토리에 대한 웹 경로입니다.
11 App.jsBaseUrl webroot 아래의 공개 js 디렉토리에 대한 웹 경로입니다.
12 앱 경로 클래스 기반이 아닌 리소스에 대한 경로를 구성합니다. 플러그인, 뷰 템플릿 및 로케일 파일의 경로를 각각 정의할 수 있는 플러그인, 템플릿, 로케일, 하위 키를 지원합니다.
13 보안.소금 해싱에 사용되는 임의의 문자열입니다. 이 값은 대칭 암호화 시 HMAC 솔트로도 사용됩니다.
14 자산.타임스탬프 적절한 도우미를 사용할 때 자산 파일 URL(CSS, JavaScript, 이미지) 끝에 특정 파일의 마지막 수정 시간인 타임스탬프를 추가합니다. 유효한 값은 −입니다.
  • (bool) false - 아무것도 하지 않습니다(기본값).
  • (bool) true - 디버그가 true인 경우 타임스탬프를 추가합니다.
  • (문자열) 'force' - 항상 타임스탬프를 추가합니다.

Databases Configuration

Database can be configured in config/app.php and config/app_local.php file. This file contains a default connection with provided parameters, which can be modified as per our choice.

The below snippet shows the default parameters and values, which should be modified as per the requirement.

Config/app_local.php

*/
   'Datasources' => [
      'default' => [
         'host' => 'localhost',
         'username' => 'my_app',
         'password' => 'secret',
         'database' => 'my_app',
         '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',
      ],
   ],
로그인 후 복사

Let us understand each parameter in detail in config/app_local.php.

Host

The database server’s hostname (or IP address).

username

Database username

password

Database password.

database

Name of Database.

Port

The TCP port or Unix socket used to connect to the server.

config/app.php

'Datasources' => [
   'default' => [
      'className' => Connection::class,
      'driver' => Mysql::class,
      'persistent' => false,
      'timezone' => 'UTC',
      //'encoding' => 'utf8mb4',
      'flags' => [],
      'cacheMetadata' => true,
      'log' => false,
      'quoteIdentifiers' => false,
      //'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],
   ],
]   
로그인 후 복사

Let us understand each parameter in detail in config/app.php.

log
Sr.No Key & Description
1

className

The fully namespaced class name of the class that represents the connection to a database server. This class is responsible for loading the database driver, providing SQL transaction mechanisms and preparing SQL statements among other things.

2

driver

The class name of the driver used to implement all specificities for a database engine. This can either be a short classname using plugin syntax, a fully namespaced name, or a constructed driver instance. Examples of short classnames are Mysql, Sqlite, Postgres, and Sqlserver.

3

persistent

Whether or not to use a persistent connection to the database.

4

encoding

Indicates the character set to use, when sending SQL statements to the server like ‘utf8’ etc.

5

timezone

Server timezone to set.

6

init

A list of queries that should be sent to the database server as and when the connection is created.

7

log

Set to true to enable query logging. When enabled queries will be logged at a debug level with the queriesLog scope.

8

quoteIdentifiers

Set to true, if you are using reserved words or special characters in your table or column names. Enabling this setting will result in queries built using the Query Builder having identifiers quoted when creating SQL. It decreases performance.

9

flags

An associative array of PDO constants that should be passed to the underlying PDO instance.

10

cacheMetadata

Either boolean true, or a string containing the cache configuration to store meta data in. Having metadata caching disable is not advised and can result in very poor performance.

Email Configuration

Email can be configured in file config/app.php. It is not required to define email configuration in config/app.php. Email can be used without it. Just use the respective methods to set all configurations separately or load an array of configs. Configuration for Email defaults is created using config() and configTransport().

Email Configuration Transport

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.

Following is the example of Email configuration transport.

'EmailTransport' => [
   'default' => [
      'className' => 'Mail',
      // The following keys are used in SMTP transports
      'host' => 'localhost',
      'port' => 25,
      'timeout' => 30,
      'username' => 'user',
      'password' => 'secret',
      'client' => null,
      'tls' => null,
      'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
   ],
],
로그인 후 복사

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.

Following is an example of Email delivery profiles.

'Email' => [
   'default' => [
   
      'transport' => 'default',
      'from' => 'you@localhost',
   ],
],
로그인 후 복사

위 내용은 CakePHP 프로젝트 구성의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!