ServBay에서 Zend Framework (Laminas) 프로젝트 생성 및 실행하기
개요
Zend Framework(현 Laminas Project의 일부)는 현대 웹 애플리케이션과 서비스를 구축하기 위한 고품질의 객체지향 컴포넌트를 제공하는 강력한 오픈소스 PHP 프레임워크입니다. 유연성, 모듈러 디자인, 높은 퍼포먼스로 유명하여 간단한 웹사이트부터 복잡한 엔터프라이즈 애플리케이션 개발까지 이상적인 선택지로 손꼽힙니다.
ServBay는 macOS 전용 로컬 웹 개발 환경으로, PHP, 다양한 웹 서버(Caddy, Nginx 등), 데이터베이스(MySQL, PostgreSQL, MongoDB 등), 캐시 서비스(Redis, Memcached 등) 및 기타 개발 도구를 통합 제공합니다. ServBay는 이 다양한 소프트웨어 패키지의 설정과 관리를 쉽게 할 수 있도록 하여, 다양한 PHP 프레임워크 프로젝트의 로컬 구축과 실행을 매우 간단하게 만들어줍니다.
이 문서에서는 ServBay 환경에서 Zend Framework (Laminas) 프로젝트를 생성, 실행하는 과정을 안내하며, ServBay가 제공하는 데이터베이스 및 캐시 서비스의 연동 사례도 함께 설명합니다.
사전 준비사항
시작 전, 아래 준비를 완료해 주세요.
- ServBay 설치: macOS 시스템에 ServBay를 정상적으로 설치 및 실행한 상태여야 합니다. 아직 설치하지 않았다면 ServBay 공식 사이트에서 다운로드 및 설치 안내를 참고하세요.
- ServBay 패키지: ServBay에 필요한 소프트웨어 패키지가 설치되고 실행 중이어야 합니다. 예를 들어:
- 최소 하나의 PHP 버전(권장: PHP 8.x 이상, 최신 Zend Framework/Laminas는 높은 PHP 버전을 요구합니다)
- 웹 서버(Caddy 또는 Nginx)
- Composer (ServBay에 기본 탑재)
- 사용할 데이터베이스 서비스(예: MySQL, PostgreSQL) 및 캐시 서비스(예: Memcached, Redis). ServBay 제어판에서 손쉽게 시작할 수 있습니다.
Zend Framework 프로젝트 생성
ServBay에서는 웹사이트 프로젝트를 /Applications/ServBay/www
디렉토리에 통일하여 저장할 것을 권장합니다. 이를 통해 ServBay가 자동으로 웹사이트를 관리하고 설정할 수 있습니다.
웹사이트 루트 디렉토리로 이동
터미널 앱을 열고 ServBay 권장 사이트 루트 디렉토리로 이동합니다:
bashcd /Applications/ServBay/www
1Composer로 프로젝트 생성
ServBay에는 Composer가 기본 포함되어 있으므로 별도 설치가 필요 없습니다. 다음과 같이 Composer
create-project
명령으로 Zend Framework (Laminas skeleton application) 새 프로젝트를 생성합니다.servbay-zend-app
이라는 하위 폴더에 프로젝트가 만들어집니다:bashcomposer create-project laminas/laminas-skeleton-application servbay-zend-app
1이 명령으로 Zend Framework (Laminas)의 스켈레톤 앱이
servbay-zend-app
폴더에 설치되고 필요한 의존성도 함께 설치됩니다.프로젝트 디렉토리로 이동
새로 생성된 프로젝트 디렉토리로 이동하세요:
bashcd servbay-zend-app
1
웹 서버 설정
Zend Framework 프로젝트에 브라우저로 접근하려면 ServBay에서 웹사이트를 추가로 설정해야 합니다.
- ServBay 제어판 열기: ServBay 앱을 실행하세요.
- 웹사이트 설정 진입: ServBay 제어판에서 웹사이트(Websites) 탭을 선택합니다.
- 새 웹사이트 추가: 좌측 하단의
+
버튼을 눌러 새로운 웹사이트를 등록합니다. - 웹사이트 정보 입력:
- 이름(Name): 예를 들어
My Zend Dev Site
등 인식하기 쉬운 이름을 지정하세요. - 도메인(Domain): 브라우저에서 접속할 도메인명 입력. 실제 도메인 충돌을 피하려면
.local
이나.test
와 같은 접미사를 권장합니다(예:servbay-zend-test.local
). ServBay가 로컬 DNS를 자동 설정합니다. - 웹사이트 유형(Website Type):
PHP
를 선택합니다. - PHP 버전(PHP Version): 사용하고 싶은 PHP 버전을 선택(예:
8.3
). 해당 PHP 버전이 ServBay에 설치되고 실행 중이어야 합니다. - 웹사이트 루트(Document Root): Zend Framework의 진입파일인
index.php
는 프로젝트의public
폴더에 있습니다. 따라서 사이트 루트 디렉토리는/Applications/ServBay/www/servbay-zend-app/public
입니다.
- 이름(Name): 예를 들어
- 저장 및 재시작: 저장(Save) 버튼을 클릭하면 ServBay가 변경사항 적용을 알리고, 확인 시 웹 서버가 설정을 재로딩하여 새 웹사이트가 활성화됩니다.
상세 설정 방법은 ServBay 문서의 첫 웹사이트 추가 챕터를 참고하세요.
"Hello ServBay!" 예제
이제 루트 URL(/
) 접속 시 "Hello ServBay!"를 출력하도록 프로젝트 코드를 수정해보겠습니다.
라우팅 및 컨트롤러 설정(module.config.php)
프로젝트 루트의
module/Application/config/module.config.php
파일을 편집하여, 아래와 같은 라우트 및 컨트롤러 설정이 포함되어 있는지 확인하세요:php<?php declare(strict_types=1); namespace Application; use Laminas\Router\Http\Literal; use Laminas\Router\Http\Segment; use Laminas\ServiceManager\Factory\InvokableFactory; return [ 'router' => [ 'routes' => [ 'home' => [ 'type' => Literal::class, 'options' => [ 'route' => '/', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'index', ], ], ], // ... 다른 라우팅 설정 ], ], 'controllers' => [ 'factories' => [ Controller\IndexController::class => InvokableFactory::class, ], ], 'view_manager' => [ 'display_not_found_reason' => true, 'display_exceptions' => true, 'doctype' => 'HTML5', 'not_found_template' => 'error/404', 'exception_template' => 'error/index', 'template_map' => [ 'layout/layout' => __DIR__ . '/../view/layout/layout.phtml', 'application/index/index' => __DIR__ . '/../view/application/index/index.phtml', 'error/404' => __DIR__ . '/../view/error/404.phtml', 'error/index' => __DIR__ . '/../view/error/index.phtml', ], 'template_path_stack' => [ __DIR__ . '/../view', ], ], // ... 기타 설정 ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49참고: 위 코드는
module.config.php
일부입니다. 기존 설정 배열과 병합하며,'home'
라우트와Controller\IndexController::class
의 팩토리 정의가 존재해야 합니다.컨트롤러 생성 혹은 수정(IndexController.php)
module/Application/src/Controller/IndexController.php
파일을 생성하거나 수정하여,indexAction
메서드가 메시지를 담은 ViewModel을 반환하도록 하세요:php<?php declare(strict_types=1); namespace Application\Controller; use Laminas\Mvc\Controller\AbstractActionController; use Laminas\View\Model\ViewModel; class IndexController extends AbstractActionController { /** * 기본 액션: 환영 페이지 표시. */ public function indexAction() { // ViewModel 생성 후 'message' 변수를 뷰로 전달 return new ViewModel([ 'message' => 'Hello ServBay!', ]); } // ... 다른 액션 메서드 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24뷰 파일 생성 혹은 수정(index.phtml)
module/Application/view/application/index/index.phtml
파일을 생성 또는 수정하고 아래 내용을 입력하세요:php<h1><?php echo $this->message; ?></h1>
1위 예제는 Zend Framework (Laminas)의 뷰 헬퍼
$this->message
로 컨트롤러에서 전달한 데이터를 출력합니다.
사이트 접속
웹 브라우저를 열고 ServBay에서 설정한 도메인, 예를 들어 https://servbay-zend-test.local
로 접속하세요.
설정이 올바르다면 Hello ServBay!
라는 페이지가 출력됩니다. 이로써 Zend Framework 프로젝트가 ServBay에서 정상적으로 실행되고 있음을 확인할 수 있습니다.
데이터베이스 및 캐시 통합 예제
ServBay는 다양한 데이터베이스 및 캐시 서비스를 제공합니다. 아래는 Zend Framework 프로젝트에서 Memcached, Redis, MySQL, PostgreSQL을 연동 및 사용하는 예시입니다.
중요: 아래 각 데이터베이스/캐시 예제는 독립된 데모입니다. 실제 프로젝트에서는 상황에 맞게 하나의 데이터베이스, 그리고 한 개 이상의 캐시 서비스를 선택해 사용하며, 의존성 주입 등으로 연결을 관리합니다. 예제 실행 전, ServBay에서 해당 서비스(MySQL, PostgreSQL, Memcached, Redis 등)를 시작해 주세요.
데이터베이스 연동 예제 - 테이블 생성
우선 Laminas DB 컴포넌트로 데이터베이스와 상호작용하여 테이블을 생성하는 간단한 예를 살펴봅니다. 아래 코드는 전체 Laminas 마이그레이션 도구 대신, 수동으로 테이블 생성 코드를 직접 실행하는 방법을 보여줍니다.
Laminas DB 컴포넌트 설치
프로젝트 루트 디렉토리에서 Composer로 Laminas DB 컴포넌트를 설치합니다:
bashcomposer require laminas/laminas-db
1데이터베이스 수동 생성
예제 실행 전, ServBay의 데이터베이스 관리 툴(phpMyAdmin, pgAdmin, MongoDB Compass 등)을 통해
servbay_zend_app
라는 데이터베이스를 수동으로 생성해야 합니다. ServBay의 MySQL/MariaDB 기본 계정은root
/password
, PostgreSQL도 동일하게root
/password
입니다.테이블 생성 스크립트 정의 및 실행(예시)
프로젝트 루트 또는 임시 경로에
create_users_table.php
와 같은 PHP 스크립트 파일을 생성하고, 아래 코드를 입력하세요:php<?php // create_users_table.php use Laminas\Db\Adapter\Adapter; use Laminas\Db\Sql\Sql; // MySQL 또는 MariaDB 사용 예시 $adapter = new Adapter([ 'driver' => 'Pdo_Mysql', // 또는 'Pdo_Pgsql' 'database' => 'servbay_zend_app', 'username' => 'root', 'password' => 'password', // ServBay 기본 비밀번호 'hostname' => '127.0.0.1', // 'port' => 3306, // MySQL 기본 포트 // 'port' => 5432, // PostgreSQL 기본 포트 ]); $sql = new Sql($adapter); // users 테이블 생성 SQL 정의 $create = $sql->createTable('users') ->addColumn(new \Laminas\Db\Sql\Ddl\Column\Integer('id', false, null, ['AUTO_INCREMENT' => true])) ->addColumn(new \Laminas\Db\Sql\Ddl\Column\Varchar('name', 255)) ->addColumn(new \Laminas\Db\Sql\Ddl\Column\Varchar('email', 255, ['UNIQUE' => true])) ->addConstraint(new \Laminas\Db\Sql\Ddl\Constraint\PrimaryKey('id')); echo "Executing SQL:\n"; echo $sql->buildSqlString($create, $adapter->getPlatform()) . "\n"; try { // SQL 실행 $adapter->query( $sql->buildSqlString($create, $adapter->getPlatform()), Adapter::QUERY_MODE_EXECUTE ); echo "Table 'users' created successfully.\n"; } catch (\Exception $e) { echo "Error creating table: " . $e->getMessage() . "\n"; }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38참고: 이 코드는 수동 테이블 생성을 위한 예시입니다. 실제 환경에서는 Laminas 마이그레이션 도구로 스키마 버전을 관리하는 것이 바람직합니다.
터미널에서 아래와 같이 실행할 수 있습니다(파일 위치에 따라 경로 조정):
bashphp create_users_table.php
1
MySQL 연동 예제
Zend Framework 컨트롤러에서 MySQL 데이터베이스에 연결하고 데이터를 조회하는 예입니다.
데이터베이스 연결 정보 설정
config/autoload/global.php
파일을 열어 MySQL 연결 정보를 입력하거나 수정하세요:php<?php // config/autoload/global.php return [ 'db' => [ 'driver' => 'Pdo_Mysql', 'database' => 'servbay_zend_app', // 반드시 실제 존재해야 함 'username' => 'root', // ServBay 기본 아이디 'password' => 'password', // ServBay 기본 비밀번호 'hostname' => '127.0.0.1', 'port' => 3306, // MySQL 기본 포트 'charset' => 'utf8mb4', ], // ... 기타 글로벌 설정 ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14컨트롤러 팩토리 설정(module.config.php)
Laminas\Db\Adapter\Adapter
를 컨트롤러에 주입하려면 팩토리 정의가 필요합니다. 만약 이미InvokableFactory
로 설정되어 있다면, 아래와 같이 직접 팩토리 함수를 구현해 대체합니다:php<?php // module/Application/config/module.config.php namespace Application; use Laminas\ServiceManager\Factory\InvokableFactory; // InvokableFactory가 다른 데서 쓸 경우 use Laminas\Db\Adapter\AdapterInterface; return [ // ... 기타 설정 'controllers' => [ 'factories' => [ Controller\IndexController::class => function($container) { // 서비스 매니저에서 DB 어댑터 얻기 $adapter = $container->get(AdapterInterface::class); // IndexController 인스턴스 생성 및 어댑터 주입 return new Controller\IndexController($adapter); }, // 다른 컨트롤러 팩토리 추가 필요 시 ], ], 'service_manager' => [ 'aliases' => [ // AdapterInterface 별칭 등록 AdapterInterface::class => 'Laminas\Db\Adapter\Adapter', ], 'factories' => [ // Adapter 팩토리 등록 'Laminas\Db\Adapter\Adapter' => \Laminas\Db\Adapter\AdapterServiceFactory::class, ], ], // ... 기타 설정 ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32참고: 위 코드 조각은
module.config.php
일부입니다. 실제 환경에 맞게 기존 배열과 병합해 설정하세요.라우트 설정(module.config.php)
MySQL 예제용으로 아래와 같이 라우팅을 추가합니다:
php<?php // module/Application/config/module.config.php namespace Application; use Laminas\Router\Http\Literal; // ... 기타 use 문 return [ 'router' => [ 'routes' => [ // ... 기존 라우트(예: 'home') 'mysql-add' => [ 'type' => Literal::class, 'options' => [ 'route' => '/mysql-add', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'mysqlAdd', ], ], ], 'mysql' => [ 'type' => Literal::class, 'options' => [ 'route' => '/mysql', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'mysql', ], ], ], ], ], // ... 기타 설정 ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35위 라우트를
'routes'
배열에 추가하세요.컨트롤러 메서드 추가(IndexController.php)
module/Application/src/Controller/IndexController.php
파일을 수정해 아래와 같이 생성자 및 메서드를 추가합니다:php<?php declare(strict_types=1); namespace Application\Controller; use Laminas\Mvc\Controller\AbstractActionController; use Laminas\View\Model\ViewModel; use Laminas\Db\Adapter\AdapterInterface; use Laminas\Db\Sql\Sql; class IndexController extends AbstractActionController { private $adapter; // 생성자에서 AdapterInterface 주입받음 public function __construct(AdapterInterface $adapter) { $this->adapter = $adapter; } /** * 기본 액션: 환영 메시지 표시. */ public function indexAction() { return new ViewModel([ 'message' => 'Hello ServBay!', ]); } /** * MySQL을 통해 users 테이블에 사용자 추가 액션. */ public function mysqlAddAction() { $sql = new Sql($this->adapter); $insert = $sql->insert('users') ->values([ 'name' => 'ServBay Demo User', 'email' => '[email protected]', // 예시 이메일 ]); $statement = $sql->prepareStatementForSqlObject($insert); $result = $statement->execute(); $message = $result->getAffectedRows() > 0 ? 'MySQL User added successfully.' : 'Failed to add MySQL user.'; return new ViewModel([ 'message' => $message, ]); } /** * MySQL을 통해 users 테이블 모든 데이터 조회 액션. */ public function mysqlAction() { $sql = new Sql($this->adapter); $select = $sql->select('users'); $statement = $sql->prepareStatementForSqlObject($select); $result = $statement->execute(); $users = []; foreach ($result as $row) { $users[] = $row; } // 결과를 JSON 문자열로 변환해 뷰로 전달 return new ViewModel([ 'users' => json_encode($users, JSON_PRETTY_PRINT), ]); } // ... 기타 액션 메서드 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77위 생성자와 두 메서드를 클래스에 추가하세요.
뷰 파일 생성
module/Application/view/application/index/mysql-add.phtml
파일 생성:php<h1><?php echo $this->message; ?></h1>
1module/Application/view/application/index/mysql.phtml
파일 생성:php<h1>MySQL Users</h1> <pre><?php echo $this->users; ?></pre>
1
2MySQL 예제 실행
ServBay의 MySQL 서비스가 실행 중임을 확인하세요. 먼저
https://servbay-zend-test.local/mysql-add
접속해 사용자 추가 메시지("MySQL User added successfully.")를 확인합니다. 이어https://servbay-zend-test.local/mysql
로 접속하면users
테이블의 데이터를 확인할 수 있습니다(JSON 형태).
PostgreSQL 연동 예제
Zend Framework 컨트롤러에서 PostgreSQL 데이터베이스와 연결, 조회하는 방법입니다.
데이터베이스 연결 정보 설정
config/autoload/global.php
파일을 열어 PostgreSQL 연결 정보를 입력하세요. 참고: MySQL과 PostgreSQL 예제를 동시에 운영하려면 별도 환경 구성이 요구될 수 있습니다. 이 예시는'db'
설정을 PostgreSQL로 교체하는 방식입니다:php<?php // config/autoload/global.php return [ 'db' => [ 'driver' => 'Pdo_Pgsql', 'database' => 'servbay_zend_app', // 반드시 실제 존재해야 함 'username' => 'root', // ServBay 기본 아이디 'password' => 'password', // ServBay 기본 비밀번호 'hostname' => '127.0.0.1', 'port' => 5432, // PostgreSQL 기본 포트 ], // ... 기타 글로벌 설정 ];
1
2
3
4
5
6
7
8
9
10
11
12
13컨트롤러 팩토리 설정(module.config.php)
(MySQL 예제와 동일)
module/Application/config/module.config.php
의controllers
와service_manager
에서 IndexController에 AdapterInterface가 제대로 주입되도록 합니다. 이미 MySQL 예제처럼 수정했다면 추가 변경 필요 없습니다.라우트 설정(module.config.php)
PostgreSQL 예제용으로 아래 라우트를 추가하세요:
php<?php // module/Application/config/module.config.php namespace Application; use Laminas\Router\Http\Literal; return [ 'router' => [ 'routes' => [ // ... 기존 라우트('home', 'mysql-add', 'mysql' 등) 'pgsql-add' => [ 'type' => Literal::class, 'options' => [ 'route' => '/pgsql-add', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'pgsqlAdd', ], ], ], 'pgsql' => [ 'type' => Literal::class, 'options' => [ 'route' => '/pgsql', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'pgsql', ], ], ], ], ], // ... 기타 설정 ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34컨트롤러 메서드 추가(IndexController.php)
module/Application/src/Controller/IndexController.php
파일에서 아래 두 메서드를 추가하세요:php<?php declare(strict_types=1); namespace Application\Controller; use Laminas\Mvc\Controller\AbstractActionController; use Laminas\View\Model\ViewModel; use Laminas\Db\Adapter\AdapterInterface; use Laminas\Db\Sql\Sql; class IndexController extends AbstractActionController { private $adapter; public function __construct(AdapterInterface $adapter) { $this->adapter = $adapter; } // ... 기존 액션(indexAction, mysqlAddAction, mysqlAction 등) /** * PostgreSQL을 통해 users 테이블에 사용자 추가 액션. */ public function pgsqlAddAction() { $sql = new Sql($this->adapter); $insert = $sql->insert('users') ->values([ 'name' => 'ServBay Demo User', 'email' => '[email protected]', // 예시 이메일 ]); $statement = $sql->prepareStatementForSqlObject($insert); $result = $statement->execute(); $message = $result->getAffectedRows() > 0 ? 'PostgreSQL User added successfully.' : 'Failed to add PostgreSQL user.'; return new ViewModel([ 'message' => $message, ]); } /** * PostgreSQL을 통해 users 테이블 전체 조회 액션. */ public function pgsqlAction() { $sql = new Sql($this->adapter); $select = $sql->select('users'); $statement = $sql->prepareStatementForSqlObject($select); $result = $statement->execute(); $users = []; foreach ($result as $row) { $users[] = $row; } return new ViewModel([ 'users' => json_encode($users, JSON_PRETTY_PRINT), ]); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65뷰 파일 생성
module/Application/view/application/index/pgsql-add.phtml
파일 생성:php<h1><?php echo $this->message; ?></h1>
1module/Application/view/application/index/pgsql.phtml
파일 생성:php<h1>PostgreSQL Users</h1> <pre><?php echo $this->users; ?></pre>
1
2PostgreSQL 예제 실행
ServBay의 PostgreSQL 서비스가 실행 중이어야 합니다. 먼저
https://servbay-zend-test.local/pgsql-add
에 접속해 사용자 추가(성공 메시지 확인). 그 다음https://servbay-zend-test.local/pgsql
에서 데이터가 정상 출력되는지 확인하세요(JSON 형태로).
Memcached 연동 예제
Zend Framework 컨트롤러에서 Memcached로 데이터 캐싱을 구현하는 예시입니다.
Memcached 어댑터 설치
프로젝트 루트의
composer.json
에 아래 의존성을 추가하세요:json// composer.json { "require": { "laminas/laminas-skeleton-application": "^1.0", "laminas/laminas-cache-storage-adapter-memcached": "^2.0" // 이 라인 추가 // ... 다른 의존성 }, // ... 기타 설정 }
1
2
3
4
5
6
7
8
9의존성 설치:
bashcomposer update
1ServBay에는 PHP의
memcached
확장이 이미 설치되어 있으므로 추가 설치 필요 없습니다.라우트 설정(module.config.php)
Memcached 예제용으로 아래 라우트를 추가하세요:
php<?php // module/Application/config/module.config.php namespace Application; use Laminas\Router\Http\Literal; return [ 'router' => [ 'routes' => [ // ... 기존 라우트 'memcached' => [ 'type' => Literal::class, 'options' => [ 'route' => '/memcached', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'memcached', ], ], ], ], ], // ... 기타 설정 ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24컨트롤러 메서드 추가(IndexController.php)
아래 메서드를
IndexController
클래스에 추가하세요:php<?php declare(strict_types=1); namespace Application\Controller; use Laminas\Mvc\Controller\AbstractActionController; use Laminas\View\Model\ViewModel; use Laminas\Cache\StorageFactory; use Laminas\Cache\Storage\StorageInterface; class IndexController extends AbstractActionController { // ... 생성자 및 기존 메서드 /** * Memcached 사용 예제 액션 */ public function memcachedAction() { // 127.0.0.1:11211이 ServBay 기본 Memcached $cache = StorageFactory::factory([ 'adapter' => [ 'name' => 'memcached', 'options' => [ 'servers' => [ ['127.0.0.1', 11211], ], 'ttl' => 300, // 300초(5분) 캐싱 ], ], 'plugins' => [ 'serializer', 'exception_handler' => ['throw_exceptions' => false], ], ]); $cacheKey = 'my_memcached_data'; $cachedData = $cache->getItem($cacheKey, $success); if (!$success) { // 캐시 미스 $cachedData = 'Hello Memcached! (Data from source, cached at ' . date('Y-m-d H:i:s') . ')'; $cache->setItem($cacheKey, $cachedData); $cachedData .= ' - CACHE MISS'; } else { // 캐시 히트 $cachedData .= ' - CACHE HIT'; } return new ViewModel([ 'message' => $cachedData, ]); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55뷰 파일 생성
module/Application/view/application/index/memcached.phtml
파일 생성:php<h1>Memcached Example</h1> <p><?php echo $this->message; ?></p>
1
2Memcached 예제 실행
ServBay에서 Memcached 서비스가 실행 중임을 확인하고,
https://servbay-zend-test.local/memcached
접속. 최초엔 "CACHE MISS" 메시지가, 300초 캐시 유효기간 내 재접속 시 "CACHE HIT" 메시지(타임스탬프 유지)가 나오면 정상입니다.
Redis 연동 예제
Zend Framework 컨트롤러에서 Redis를 활용한 데이터 캐싱/스토리지 예제입니다.
Redis 어댑터 설치
composer.json
에 아래 의존성을 추가하세요:json// composer.json { "require": { "laminas/laminas-skeleton-application": "^1.0", "laminas/laminas-cache-storage-adapter-redis": "^2.0", // 이 라인 추가 "ext-redis": "*" // PHP용 redis 확장 확인 // ... 다른 의존성 }, // ... 기타 설정 }
1
2
3
4
5
6
7
8
9
10의존성 설치:
bashcomposer update
1ServBay에는 PHP
redis
확장이 미리 설치되어 있습니다.라우트 설정(module.config.php)
Redis 예제 라우트를 추가하세요:
php<?php // module/Application/config/module.config.php namespace Application; use Laminas\Router\Http\Literal; return [ 'router' => [ 'routes' => [ // ... 기존 라우트 'redis' => [ 'type' => Literal::class, 'options' => [ 'route' => '/redis', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'redis', ], ], ], ], ], // ... 기타 설정 ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24컨트롤러 메서드 추가(IndexController.php)
아래 메서드를 클래스에 추가하세요:
php<?php declare(strict_types=1); namespace Application\Controller; use Laminas\Mvc\Controller\AbstractActionController; use Laminas\View\Model\ViewModel; use Laminas\Cache\StorageFactory; use Laminas\Cache\Storage\StorageInterface; class IndexController extends AbstractActionController { // ... 생성자 및 기존 메서드 /** * Redis 사용 예제 액션 */ public function redisAction() { // 127.0.0.1:6379가 ServBay 기본 Redis 포트 $cache = StorageFactory::factory([ 'adapter' => [ 'name' => 'redis', 'options' => [ 'server' => [ 'host' => '127.0.0.1', 'port' => 6379, // 'database' => 0, // 'password' => null, ], 'ttl' => 300, ], ], 'plugins' => [ 'serializer', 'exception_handler' => ['throw_exceptions' => false], ], ]); $cacheKey = 'my_redis_data'; $cachedData = $cache->getItem($cacheKey, $success); if (!$success) { $cachedData = 'Hello Redis! (Data from source, cached at ' . date('Y-m-d H:i:s') . ')'; $cache->setItem($cacheKey, $cachedData); $cachedData .= ' - CACHE MISS'; } else { $cachedData .= ' - CACHE HIT'; } return new ViewModel([ 'message' => $cachedData, ]); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56뷰 파일 생성
module/Application/view/application/index/redis.phtml
파일 생성:php<h1>Redis Example</h1> <p><?php echo $this->message; ?></p>
1
2Redis 예제 실행
ServBay에서 Redis 서비스를 실행하고
https://servbay-zend-test.local/redis
접속. 첫 접속에는 "CACHE MISS", 이후에는 "CACHE HIT" 메시지가 나오고, 시간은 캐시 유효기간 내에선 바뀌지 않으면 정상입니다.
마무리
이제 ServBay 로컬 개발 환경에서 Zend Framework (Laminas) 프로젝트를 생성, 설정, 실행하는 방법을 익혔습니다. ServBay의 웹사이트 관리 기능으로 웹 서버의 루트 디렉토리를 쉽게 지정하고, MySQL/ PostgreSQL 등 데이터베이스, Memcached/ Redis 캐시를 프로젝트에 연동하는 방법도 살펴보았습니다.
ServBay는 개발 환경 구축과 관리를 단순화하여 개발자가 코드에 집중할 수 있도록 돕습니다. 다양한 소프트웨어 패키지와 유연한 설정 덕분에, 로컬에서 실제 운영 환경 수준의 개발 테스트가 가능하며 개발 효율성을 높일 수 있습니다.