목차
환경변수
일반 구성
Databases Configuration
Config/app_local.php
config/app.php
Email Configuration
Email Configuration Transport
Email Delivery Profiles
백엔드 개발 PHP 튜토리얼 CakePHP 프로젝트 구성

CakePHP 프로젝트 구성

Sep 10, 2024 pm 05:25 PM
php cakephp PHP framework

이 장에서는 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제

PHP 튜토리얼
1596
276
Edge PDF 뷰어가 작동하지 않습니다 Edge PDF 뷰어가 작동하지 않습니다 Aug 07, 2025 pm 04:36 PM

TestHepdFinanotherAppTodeMineifTheissueiswithTheFileoredge.2

Explorer 패널에 중점을 둔 코드 바로 가기 Explorer 패널에 중점을 둔 코드 바로 가기 Aug 08, 2025 am 04:00 AM

VSCODE에서는 바로 가기 키를 통해 패널과 편집 영역을 빠르게 전환 할 수 있습니다. 왼쪽 탐색기 패널로 이동하려면 Ctrl Shift E (Windows/Linux) 또는 CMD Shift E (Mac)를 사용하십시오. ctrl` 또는 esc 또는 ctrl 1 ~ 9를 사용하려면 편집 영역으로 돌아갑니다. 마우스 작동과 비교할 때 키보드 단축키는 더 효율적이며 인코딩 리듬을 방해하지 않습니다. 다른 팁으로는 다음과 같습니다.

하위 프로세스를 실행하는 예제로 이동하십시오 하위 프로세스를 실행하는 예제로 이동하십시오 Aug 06, 2025 am 09:05 AM

OS/EXEC 패키지를 사용하여 하위 프로세스를 실행하고 Exec.Command를 통해 명령을 작성하되 즉시 실행하지 마십시오. 2. .output ()로 명령을 실행하고 stdout을 잡으십시오. 종료 코드가 0이 아닌 경우 exec.exiterror를 반환하십시오. 3. .start ()를 사용하여 차단하지 않고 프로세스를 시작하고 .stdoutpipe ()와 결합하여 출력을 실시간으로 스트리밍하십시오. . 5. exec.exiterror는 좀비 프로세스를 피하기 위해 실패한 명령의 종료 코드와 STDERR을 얻으려면 처리되어야합니다.

수정 : Windows 업데이트가 설치되지 않았습니다 수정 : Windows 업데이트가 설치되지 않았습니다 Aug 08, 2025 pm 04:16 PM

runthewindowsupdateTrouBleShootErviaSettings> 업데이트 및 보안> 문제 해결을 해소 적으로 문제를 해결합니다 .2

PHP 특성, 추상 클래스 및 실제 사용 사례와의 인터페이스를 비교하고 대조하십시오. PHP 특성, 추상 클래스 및 실제 사용 사례와의 인터페이스를 비교하고 대조하십시오. Aug 11, 2025 pm 11:17 PM

interfacestodefinecontractsforUnratedClasses, theyimplesmentspecificmethods를 보장합니다

PHP에서 배열로 작업하는 방법 PHP에서 배열로 작업하는 방법 Aug 20, 2025 pm 07:01 PM

phparrayshandledataCollectionsefficiativeStructure; heidearecreatedwitharray () 또는 [], ac

Break, 계속 및 Goto를 사용하여 Foreach 내에서 유량 제어를 마스터 링 Break, 계속 및 Goto를 사용하여 Foreach 내에서 유량 제어를 마스터 링 Aug 06, 2025 pm 02:14 PM

BreakexitsTheloopimmed SeeforFindingAtArget, 이상적으로 THEFIRSTMATCH.2.ContInuesKIPSTheCurrentitation, 유용한 ortipilteringItemSliketemporaryFiles.3.gotoJumpStoalabeledStatement, 허용 가능한 원형 곡물 류 횡단 부산물

수정 : 이더넷 '미확인 네트워크' 수정 : 이더넷 '미확인 네트워크' Aug 12, 2025 pm 01:53 PM

RETARTYOURROUTERANDOCPUTERESOLVETEMPORARYGLITCES.2.RUNTHENTERWORKTROUBLESHOTERVIATHESTEMTRAYTOAUAUTOMALICALLYFIXCOMMONISS.3.RENEWTHEIPADDRESSUSINGCOMMANDPROMPROMPTASADMINSTRATORBYRUNNINGIPCONFIG/RELEART, IPCONFIG/RENEET, NETSHWINSOCKRETSHONT, 및 rENTOKRETSHONTONT, and NETSHWINSOCKREST

See all articles