수색…


새 컨트롤러 만들기

namespace App\Controller;

class PostsController extends AppController {

    public function initialize(){
        parent::initialize();
        // code that you want to run before every action
    }
    public function view($id) {
       //Your code here
    }
}

컨트롤러에 beforeFilter () 메서드 추가

beforeFilter () 메서드는 컨트롤러에서 다른 메서드를 실행하기 전에 실행됩니다.

먼저 컨트롤러 파일에서 클래스를 정의하기 전에 이벤트 네임 스페이스를 사용하십시오.

use Cake\Event\Event;

컨트롤러에서 beforeFilter () 메서드를 아래와 같이 추가합니다.

public function beforeFilter(Event $event) {
    parent::beforeFilter($event);
}

또는 initialize() 메서드를 사용할 수 있습니다.

public function initialize(){
    parent::initialize();
}

뷰에 변수 전달하기

한 번에 볼 수 있도록 각 변수 전달

$this->set('color', 'pink');
$this->set('color', $color);

여러 변수를 전달하여 compact () 함수를 통해 함께 봅니다.

$color1 = 'pink';
$color2 = 'red';
$this->set(compact('color1', 'color2'));

$ _POST에 해당하는 게시물 데이터 검색 중

배열로 게시물 데이터를 검색 할 수 있습니다.

$post_data= $this->request->data;

특정 키의 게시물 데이터를 검색 할 수 있습니다.

$this->request->data['field'];

특정 키 값 검색

$this->request->data('key_name');

중첩 된 배열의 특정 키 값 검색

$this->request->data('data.subfield');

배열 표기법과 data() 메서드의 차이점은 data() 가 오류 안전하다는 것입니다. 키가 배열에 없으면 null 반환합니다.

그렇게하기 위해

if(isset($this->request->data['field']) && $this->request->data['field']) { ...}

넌 할 수있어

if($this->request->data('field')) { ...}

CakePHP 3.4.x +

모든 데이터 얻기 :

$this->request->getData();

특정 키 얻기 :

$this->request->getData('key');

getData 함수에 사용할 수있는 데이터를 설정하려면 다음과 같이해야합니다.

$this->request = $this->request->withData('some_key_on_the_fly', 'value');
$some_key_on_the_fly = $this->request->getData('some_key_on_the_fly');

정적 데이터가있는 컨트롤러에서 모델을 업데이트하는 데 유용합니다.

컨트롤러에 다른 모델로드

기본적으로 CakePHP는 컨트롤러에서 관련 모델을로드합니다. 컨트롤러에 다른 모델을로드하려면 loadModel () 메서드를 사용하십시오.

$this->loadModel('Articles');

또는 비행 중에로드

$table = TableRegistry::get('Articles');
$table->find();

컨트롤러에서 다른 페이지로 리디렉션

애플리케이션 내로 리디렉션 (특정 컨트롤러의 다른 동작).

return $this->redirect([
    'controller' => 'myController',
    'action' => 'myAction'
]);

리퍼러 페이지로 리디렉션

return $this->redirect($this->referer());

애플리케이션 외부 또는 특정 URL로 리디렉션

return $this->redirect("http://stackoverflow.com/users/1793428/haresh-vidja");

리디렉션 URL에서 액션에 변수 전달

메서드 매개 변수로 URL에 변수 전달

return $this->redirect([
    'controller' => 'users',
    'action' => 'profile',
    $id
]);

URL은 다음과 같아야합니다. http : // your_app_url / users / profile / {id}

profile () 메소드의 UsersController.php 파일에서

class UsersController extends Controller {
    public function profile($id=null) {
        $userData=$this->Users->get($id);
    }
}

URL의 변수를 쿼리 문자열 로 전달

return $this->redirect([
    'controller' => 'users',
    'action' => 'profile',
    '?'=>['id'=>$id]
]);

URL은 다음과 같아야합니다. http : // your_app_url / users / profile /? id = {id}

profile () 메소드의 UsersController.php 파일에서

class UsersController extends Controller {
    public function profile() {
        $userData=$this->Users->get($this->request->query('id'));
    }
}

응용 프로그램의 레이아웃 설정 또는 변경

전체 응용 프로그램의 기본 레이아웃 설정 합니다 . 즉, /src/Template/Layout/admin.ctp에 레이아웃 파일을 만들었습니다.

class AppsController extends Controller {

    public function beforeFilter(Event $event) {
        parent::beforeFilter($event);
        $this->viewBuilder()->layout('admin'); // For Version >= 3.1 or
        $this->layout = 'admin'; // for version < 3.1
        
        // your other code should be here
    }
}

응용 프로그램의 특정 동작에 대한 기본 레이아웃 설정 합니다 . 즉, 응용 프로그램은 /src/Template/Layout/login.ctp의 로그인 페이지에서 다른 레이아웃을가집니다.

class UsersController extends Controller {

    public function login() {

        $this->viewBuilder()->layout('login'); // For Version >= 3.1 or
        $this->layout = 'login'; // for version < 3.1
        
        //your other code should be here
    }
}

특정 컨트롤러의 레이아웃 변경. 즉, 특정 컨트롤러의 모든 메소드에 대해 다른 레이아웃이 필요합니다.

class UsersController extends Controller {

    public function beforeFilter(Event $event) {
        parent::beforeFilter($event);

        $this->viewBuilder()->layout('user_layout'); // For Version >= 3.1 or
        $this->layout = 'user_layout'; // for version < 3.1
        
        //your other code should be here
    }
}

Ajax 요청 레이아웃 설정

일반적으로 AJAX에서 CSS, JS로드가 필요하지 않습니다. 또한 다른 HTML 코드도 생략합니다.

/ src / Template / Layout에 ajax.ctp 파일을 만들고 코드가 있어야합니다.

<?php 
    $this->fetch('content');

AppsController.php에서 전체 애플리케이션을위한 AJAX 기반 레이아웃 설정

class AppsController extends Controller {

public function beforeFilter(Event $event) {
    parent::beforeFilter($event);
    if($this->request->isAjax())
    {
        $this->viewBuilder()->layout('ajax'); // For Version >= 3.1 or
        $this->layout = 'ajax'; // for version < 3.1

    }
    else
    {
        $this->viewBuilder()->layout('admin'); // For Version >= 3.1 or
        $this->layout = 'admin'; // for version < 3.1
    }
    
    // your other code should be here
}

}

CakePHP에서 컴포넌트로드

두 가지 방법으로 구성 요소를로드 할 수 있습니다.

  1. 컨트롤러의 $ components 속성을 초기화하거나 무시합니다.
  2. 컨트롤러의 initialize () 메소드에서 loadComponent () 메소드 사용.

Way-1 AppsController.php에 의해로드 된 구성 요소를 덮어 써야 하나 이상의 구성 요소를로드해야합니다.

class UsersController extends AppController {
    public $components = ['RequestHandler','Auth','Flash']; 
}

Way-2 특정 컨트롤러에 동적으로 구성 요소를로드해야하는 경우이 방법을 사용합니다. 하나의 구성 요소로드

class UsersController extends AppController {
    public function initialize() {
        parent::initialize();
        $this->loadComponent("RequestHandler"); // load specific component
        $this->loadComponent(["RequestHandler","Auth","Flash"]); // load specific component
    }
}

initilaize () 메소드 란 무엇입니까?

initialize ()는 CakePHP 버전 3.0 이상에서 소개되었습니다.

코드 구조는 beforeFilter () 메소드와 같습니다. 그러나 beforeFilter ()와 initialize () 사이에는 많은 차이점이 있습니다.

  1. initialize ()는 생성자가 호출 된 후에 항상 호출됩니다. 하지만 beforeFilter ()는 특정 컨트롤러에서 동작 메서드가 발견되지 않으면 호출하지 않습니다.
  2. initialize () 메서드는 일반적으로 새로운 구성 요소 및 도우미 추가 같은 것을 초기화하는 데 사용됩니다. 그러나 beforeFilter ()는 일반적으로 일부 전역 로직 부분을 실행하는 데 사용됩니다.

$ _GET에 해당하는 쿼리 문자열 데이터를 검색하십시오.

쿼리 문자열 데이터를 Array로 검색 할 수 있습니다.

$post_data= $this->request->query;

특정 키의 게시물 데이터를 검색 할 수 있습니다.

$this->request->query['field'];

특정 키 값 검색

$this->request->query('key_name');

중첩 된 배열의 특정 키 값 검색

$this->request->query('data.subfield');

테이블 (모델) 클래스 만들기

사용자 모델 클래스를 만드는 방법

namespace App\Model\Table;
use Cake\ORM\Table;

class UsersTable extends Table {
    public function initialize(array $config) {
        $this->table('users'); //define table name
        $this->displayField('username'); // unique or other special field of users table
        $this->primaryKey('id'); // primary key of users table
        $this->tablePrefix('prefix_'); // if prefix set tablename should be prefix_users

        // your other code here
    }

    // your other methods here
}

CakePHP의 모델 연관성

CakePHP에서 정의 할 수있는 4 가지 유형의 연관성 (관계)이 있습니다.

class PostsTable extends Table {
    public function initialize(array $config) {

        // table initialization code should be here

        $this->belongsTo('Authors', [
            'className' => 'Authors',
            'foreignKey' => 'author_id',
            'joinType' => 'INNER',
        ]);
        $this->hasMany('Tags');
        $this->hasOne('Categories');
        $this->hasAndBelongsToMany('Topics');
    }
}

위의 예에서는 4 가지 유형의 관계를 볼 수 있습니다.

게시물 저자 (일대일)에 속하며 , 이는 posts 테이블에 authors 테이블의 id 와 연결된 하나의 외부 키 author_id 가 있음을 의미합니다.

포스트 는 많은 태그 ( 일대 다 ) 를 가지고 있습니다. tags 테이블의 의미는 posts 테이블의 id 와 연관된 하나의 외래 키 post_id 집니다.

포스트 (하나 하나에 하나에 많은) 하나 개의 태그를 가지고, 그것은 의미 posts 테이블은 하나의 외래 키가 category_id 와 관련된 idcategories 테이블을.

포스트 토픽 (Many to Many)에 속해 있으며, poststopics 테이블 사이의 많은 관계입니다. 많은 관계를 유지하기 위해서는 세 번째 테이블, 테이블, 테이블 이름을 posts_categories 해야 생성해야합니다. 아래 표와 같이이 표의 입력란

  1. id (테이블의 기본 키)
  2. post_id ( posts 테이블의 외래 키)
  3. topic_id ( topics 테이블의 외래 키)


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow