레일즈는 bin 폴더에 있는 bundle, rails, rake 명령어들이 편한함을 제공하고 이를 통해서 빠른 웹개발이 가능하게 하는데요
특히나 Rails의 Scaffold기능은 웹개발에 지친 개발자들을 매료시켰지요
CakePHP도 이제는 이를 능가하는 막강한 명령어를 제공하는데요
명령어는 app/Console 에 있습니다.
여기를 보면 cake명령어가 있는데는 이를 이용하면 힘든 타이핑 없이 바로 자동으로 모델, 컨트롤러, 뷰를 제작할수 있습니다.
특히 저는 cake.bat가 있어서 감명 받았는데요
윈도우를 쓰는 개발자도 배려하여 만든 CakePHP의 명령어 입니다. 윈도우 사용자는 cake.bat를 실행하면 됩니다.
하여간 이 cake(cake.bat)를 실행하려면 콘솔상에서 php명령어가 실행될수 있어야 합니다.
이 조건만 충족된다면 cake명령어를 쓰는데는 아무런 제약이 없습니다.
이 cake명령어도 기능이 방대한데 우선 우리가 볼것은 bake입니다.
cakePHP이니깐 만들어 내는것은 빵을 만드는 bake입니다. 재미있지요
bake는 명령어로 cake bake 이렇게 실행합니다.
그럼 bake를 이용해 간단한 게시판을 만들어 보겠습니다.
우선 테이블을 만들어야 되는데요
CakePHP는 Rails처럼 마이그레이션은 기본 지원하지 않습니다.
좋은점인지 나쁜점인지는 모르겠습니다.
꼭 필요하다면 Migration지원하는 플러그인들은 있는듯 하니 찾아서 이용하시기 바랍니다.
테이블은
CREATE TABLE `boards` (
`id` int(11) NOT NULL,
`title` varchar(60) NOT NULL,
`content` text NOT NULL,
`modified` datetime NOT NULL,
`created` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB ROW_FORMAT=DYNAMIC DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
이렇게 구성했습니다.
CakePHP에서 특별하게 취급되는 필드가 있는데
id, 테이블명_id, 테이블명_count, modified, created등입니다.
Rails경험해 보았다면 바로 알겠지만 id는 테이블의 기본키 테이블명_id는 "테이블명"과 연관되는 외래키
테이블명_count는 하위의 "테이블명"의 카운터, modified는 자동 수정날짜저장 필드
created는 자동 저정날자 필드입니다.
우선 테이블은 이런식으로 구성하고
app/Console로 이동하여
./cake bake (윈도우 사용자라면 cake.bat bake)
Welcome to CakePHP v2.5.1 Console
---------------------------------------------------------------
App : app
Path: /home/toughjjh/cakephp/app/
---------------------------------------------------------------
Interactive Bake Shell
---------------------------------------------------------------
[D]atabase Configuration
[M]odel
[V]iew
[C]ontroller
[P]roject
[F]ixture
[T]est case
[Q]uit
What would you like to Bake? (D/M/V/C/P/F/T/Q)
>
이런 화면이 나오게 됩니다.
여러가지 메뉴가 있는데 역시 우리에게 중요하것은 모델,컨트롤러,뷰를 만들어 내는것이지요
그중 우선 모델을 제일 먼저 만들어야됩니다.
M을 누르고 엔터를 칩니다.
---------------------------------------------------------------
Bake Model
Path: /home/toughjjh/cakephp/app/
---------------------------------------------------------------
Use Database Config: (default/test)
[default] >
어느 데이터베이스 설정을 사용할것인지 묻습니다. 그냥 엔터 또는 default를 치고 엔터
Possible Models based on your current database:
1. Boards
Enter a number from the list above,
type in the name of another model, or 'q' to exit
>
현재 테이블을 검색하여 목록을 나타내게 됩니다.
현재는 Board밖에 없으므로 Board를 선택합니다.
1 또는 Boards 라고 치고서 엔터
Would you like to supply validation criteria
for the fields in your model? (y/n)
[y] >
유효성 검사를 할것인지 묻습니다. 그냥 엔터 또는 y를 치고 엔터
Field: id
Type: integer
---------------------------------------------------------------
Please select one of the following validation options:
---------------------------------------------------------------
1. alphaNumeric 18. maxLength
2. between 19. mimeType
3. blank 20. minLength
4. boolean 21. money
5. cc 22. multiple
6. comparison 23. naturalNumber
7. custom 24. notEmpty
8. date 25. numeric
9. datetime 26. phone
10. decimal 27. postal
11. email 28. range
12. equalTo 29. ssn
13. extension 30. time
14. fileSize 31. uploadError
15. inList 32. url
16. ip 33. userDefined
17. luhn 34. uuid
35 - Do not do any validation on this field.
---------------------------------------------------------------
or enter in a valid regex validation string.
Alternatively [s] skip the rest of the fields
[35] >
id필드에 관한 유효성은 어떤것으로 할거인지 묻습니다.
그냥 엔터를 칩니다.
Field: id
Type: title
[24] >
다음은 제목입니다.
비어서 입력되지 않게 하는 24번을 선택합니다. 선택되어 있으면 그냥 엔터
Would you like to add another validation rule
or skip the rest of the fields? (y/n/s)
더 추가할 유효성검사가 있는지 묻습니다.
n를 치고서 엔터
Field: content
Type: text
[24] >
다음은 내용입니다.
역시 24번을 입력하고 엔터
더 추가할것 없다고하고 다음으로
나머지 필드들도 35번으로 넘기고 나면
Would you like to define model associations
(hasMany, hasOne, belongsTo, etc.)? (y/n)
관계설정할것인지를 묻습니다.
이 역시 중요한 기능인데 지금은 설정되지 않았으므로
n을 치고 엔터
---------------------------------------------------------------
The following Model will be created:
---------------------------------------------------------------
Name: Board
DB Table: `cakephp`.`boards`
Validation: Array
(
[title] => Array
(
[notEmpty] => notEmpty
)
[content] => Array
(
[notEmpty] => notEmpty
)
)
---------------------------------------------------------------
Look okay? (y/n)
이렇게 만들어도 되겠냐고 묻습니다. 잘 만들어 졌습니다. y를 치고 엔터
Creating file /home/toughjjh/cakephp/app/Model/Board.php
라는 메세지가 나옵니다.
해당 경로로 가보면 모델이 잘 만들어져 있습니다.
이렇게 질문에 대답한것만으로 제목과 내용의 유효성을 체크하는 모델이 만들어졌습니다.
다음은 콘트롤러를 제작할 차례입니다.
c 를 눌러서 콘트롤러 제작을 선택하고 넘어가면
데이터베이스 선택화면은 모델과 동일하고
만들 콘트롤러 선택화면도 모델과 동일합니다.
선택후에
---------------------------------------------------------------
Baking BoardsController
---------------------------------------------------------------
Would you like to build your controller interactively? (y/n)
[y] >
그대로 엔터 또는 y를 치고서 엔터
Would you like to use dynamic scaffolding? (y/n)
[n] >
그대로 엔터 또는 n를 치고서 엔터
Would you like to create some basic class methods
(index(), add(), view(), edit())? (y/n)
[n] >
y를 치고서 엔터 (기본이 n으로 되어있음)
Would you like to create the basic class methods for admin routing? (y/n)
[n] >
관리자 기본 기능을 만들것이냐고 물어보는데
나중에 필요할때는 y를 치면 되겠습니다. 우선은 n
Would you like this controller to use other helpers besides HtmlHelper and FormHelper? (y/n)
[n] >
n로 넘어가고
Would you like this controller to use other components besides PaginatorComponent? (y/n)
[n] >
n로 넘어간다
Would you like to use Session flash messages? (y/n)
[y] >
y로 넘어간다
---------------------------------------------------------------
The following controller will be created:
---------------------------------------------------------------
Controller Name:
Boards
Components:
Paginator, Session
---------------------------------------------------------------
Look okay? (y/n)
이렇게 만들어도 되겠냐고 묻습니다. 이번에도 잘 만들어 졌습니다. y를 치고 엔터
Creating file /home/toughjjh/cakephp/app/Controller/BoardsController.php
역시 해당경로에 콘트롤러 파일이 생성되었습니다.
이번에는 뷰를 생성해보겠습니다.
V를 눌러서 메뉴로 들어가면 역시 기본 질문은 동일하고
Would you like bake to build your views interactively?
Warning: Choosing no will overwrite Boards views if it exist. (y/n)
[n] >
해당 뷰가 겹치면 덮어쓰냐는 질문입니다.
넘어가면 역시 파일이 생성되었다는 메세지가 나옵니다.
이렇게 해서 모델, 콘트롤러, 뷰를 모두 생성하였습니다.
이제 브라우저에서 주소/boards로 접속하면
자동으로 만들어진 내 게시판이 보이게 됩니다.