가볍고 사용하기 쉬운 PHP 프레임 워크.
Dejframework는 간단하고 최소한의 PHP MVC 프레임 워크입니다. 간결함, 단순성 및 이해력에 중점을 둡니다. 구문은 주로 Laravel에서 영감을 얻었습니다. Dejframework는 ATA Marzban이 학사 학위의 최종 프로젝트를 위해 개발했습니다.
#설치
composer install 실행하십시오.요청이 올 때 무엇을 해야하는지 프레임 워크를 알기 위해서는 /app/routes.php에서 응용 프로그램의 경로를 설정해야합니다. 쉽게 이루어집니다.
경로는 지정된 메소드가 지정된 URL에 요청 된 경우 HTTP 방법, URL 및 대상으로 구성됩니다. 경로를 설정하지 않고 실행되는 것은 없습니다. 대상으로 폐쇄를 통과 할 수 있습니다.
[/app/routes.php]
Route:: set ( " GET " , " / " , function (){
return " Hello World! " ;
});이 코드는 yoursite.com에서 사이트를 방문하면 "Hello World"를 출력합니다.
[/app/routes.php]
Route:: set ( " GET " , " /some/url " , function (){
return " This is some url! " ;
});이 코드는 "이것은 URL입니다!" a yoursite.com/some/url에서 귀하의 사이트를 방문한 경우.
[/app/routes.php]
Route:: set ( " POST " , " /do/something " , function (){
return " Here you should write your own code to do the things you want. " ;
});이 코드는 게시물 메소드와 함께 yoursite.com/do/something을 방문하면 실행됩니다. (양식 또는 API 통화에서)
클로저 또는 컨트롤러에서 문자열, 객체, 배열 또는보기 (나중에 논의)를 반환 할 수 있습니다. 문자열은 직접 출력되며 객체 또는 뷰는 자동으로 JSON 및 출력으로 변환되며 뷰는 출력으로 렌더링됩니다.
다음 부분에서는 폐쇄 대신 컨트롤러로 경로를 지시하는 방법을 배웁니다.
MVC 패턴의 모범 사례는 응용 프로그램 논리를 컨트롤러에 넣어야한다고 생각합니다.
[/app/controllers/YourController.php]
<?php
namespace app controllers;
class YourController extends dej mvc Controller
{
public static function yourAction ()
{
return " This is the right way to do it! " ;
}
}중요 : 위의 예에서 볼 수 있듯이 PSR-0 자동 로더가 올바르게 작동하려면 응용 프로그램에 클래스를 추가 할 때 다음 규칙을 따라야합니다.
이제 컨트롤러를 작동시키는 방법을 계속 배우겠습니다.
[/app/routes.php]
Route:: set ( " GET " , " / " , " YourController@YourAction " );지정된 컨트롤러의 지정된 조치는 경로가 트리거 될 때 실행됩니다.
끊임없이 수업을 인스턴스화하고 의존성을 전달하면 PHP 개발에서 반복적 인 작업이 될 수 있습니다. dej 앱 서비스 제공 업체는이 프로세스를 가능한 한 건조하게 만드는 것을 목표로합니다. 이 서비스 제공 업체를 사용하면 각 파일에 사용 문을 추가하고 종속성을 통과 할 필요가 없습니다. 이 예를 들어보세요 :
/**
* Without a Service Provider
* when you want to build a query
*/
use dej db Connection ;
$ connection = Connection:: getInstance ();
use dej db Query ;
$ query = new Query ( $ connection );
$ result = $ query -> select ()-> from ( ' someTable ' )-> getAll ();
return $ result ;그리고 이것은 쿼리 빌더를 사용할 때마다 반복해야합니다. 이제 서비스 제공 업체 사용 :
use dej App ;
return App:: Query ()-> select ()-> from ( ' some_table ' );그게 다야! dej/app.php 를보고 어떻게 작동하는지 확인하십시오. 'query'라는 정적 메소드가 앱 클래스에서 호출됩니다. 쿼리 클래스를 인스턴스화하고 생성자 매개 변수로 연결 인스턴스를 전달합니다. 케이크 한 조각!
#request dejhttpRequest 클래스를 요청하는 것과 쉽게 상호 작용할 수있게하고 다음 예제를 살펴보십시오.
//check if request is ajax or not
$ result = App:: Request ()-> isAjax ();
//returns $_GET['name'];
$ result = App:: Request ()-> get ( ' name ' );
//returns $_POST['name'];
$ result = App:: Request ()-> post ( ' name ' );
//returns $_REQUEST;
$ result = App:: Request ()-> all (); #Response dejhttpResponse 클래스는 응답 매개 변수를 쉽게 설정할 수있게 해주므로 HTTP 응답 코드 또는 헤더를 설정하려면 컨트롤러에서 응답을 반환해야합니다. 다음 예제를 살펴보십시오.
class IndexController extends dej mvc Controller
{
public static function index ()
{
return App:: Response ()-> code ( 404 )-> header ( ' HTTP/1.1 404 Not Found ' );
}
}쉽게 리디렉션 할 수 있습니다.
//in the controller
return App:: Response ()-> redirect ( ' /login ' );
//redirect with errors
App:: Response ()-> redirect ( ' / ' )-> withErrors ([ ' login ' => ' login unsuccessful! maybe password is wrong. ' ]);오류로 리디렉션하면 오류가 세션에 깜박입니다 (나중에 논의).
구성 : 먼저 /config.json 에 데이터베이스 구성을 입력하십시오. Dejframework는 3 계층 아키텍처의 데이터베이스를 처리합니다.
레이어 1- 데이터베이스 연결 객체 : 싱글 톤 초록 클래스를 확장합니다. 그 의미는 처음이라고 불리는 것은 한 번만 인스턴스화된다는 것입니다. dejframework의 다른 서비스도 다음과 같습니다. 쿼리를 실행할 때마다 DB에 연결하는 오버 헤드를 방지합니다. 사용 방법은 다음과 같습니다.
//simple query
$ result = App:: Connection ()-> executeQuery ( " SELECT * FROM some_table " );
//NonQuery: a query that doesn't return rows, only the number of affected rows.
$ result = App:: Connection ()-> executeNonQuery ( " DELETE FROM some_table WHERE some_field = 'some_value' " );
//A Query using prepared statements, To protect against SQL Injection.
$ result = App:: Connection ()-> executeQuery ( " SELECT * FROM some_table WHERE some_field = ? " , [ " some_value " ]);
//A Query using prepared statements, To protect against SQL Injection. With Multiple Parameters.
$ result = App:: Connection ()-> executeQuery ( " SELECT * FROM some_table WHERE some_field = ? AND another_field = ? " , [ $ some_value , " another_value " ]);
//A Query using prepared statements, To protect against SQL Injection. With Named Parameters.
$ result = App:: Connection ()-> executeQuery ( " SELECT * FROM some_table WHERE some_field = :some_value_name
AND another_field = :another_value_name " ,
[ " :some_value_name " => $ some_value ,
" another_value_name " => " another_value " ]); use dejApp; .
레이어 2- 쿼리 빌더 : 이 클래스는 쿼리를 빌드하고 연결 클래스를 사용하여 보안 준비 된 문을 사용하여 실행합니다. 각각의 새 쿼리에 대해 인스턴스화해야합니다. 이는 Service Povider 섹션 예제에서 본 것처럼 App::Query() 입력 할 때마다 /dej /앱에 의해 자동으로 수행됩니다. 메소드 체인을 사용하여 쿼리를 구축 할 수 있습니다. 아래 예제를 살펴보십시오.
$ result = App:: Query ()-> select ()-> from ( ' users ' )-> getAll ();
$ result = App:: Query ()-> select ()-> from ( ' users ' )-> getOne ();
$ result = App:: Query ()-> select ()-> from ( ' users ' )-> getJson ();
$ query = App:: Query ()-> select ()-> from ( ' users ' )-> getQuery (); 보시다시피, Dej Query Builder를 사용하는 것은 간단하고 Call App :: Query ()를 사용하고 새로운 종속성 주입 된 쿼리 클래스를 자동으로 전달 한 다음, (), (), () 등과 같은 취향에 대한 취향 조건을 추가하여 최종 결과 getOne() getAll() ), 모두 (get) getJson() ) 또는 구성 쿼리 ( getQuery() ). 결과는 쉽게 사용할 수있는 stdclass 형식으로 가져옵니다. 쿼리 끝에 GET 메소드 중 하나를 사용하지 않으면 결과가 가져 오지 않을 것입니다. 또한 여러 줄과 여러 단계로 메소드를 체인하여 일부 조건으로 변경할 수 있습니다.
$ query = App:: Query ()-> select ();
if ( $ somecondition == true ) $ query -> from ( ' users ' );
else $ query -> from ( ' another_table ' );
$ result = $ query -> getAll ();다음 예제에서 쿼리 빌더에서 사용할 수있는 다른 방법을 보자.
//All queries will be executed using prepared statements and parameters will be handled automatically.
//SELECT Queries:
$ result = App:: Query ()-> select ()-> from ( ' users ' )-> where ( ' id ' , ' = ' , ' 22 ' )-> getAll ();
//you can omit the operator and it uses '=' by default
$ result = App:: Query ()-> select ()-> from ( ' users ' )-> where ( ' id ' , ' 22 ' )-> getAll ();
$ result = App:: Query ()-> select ()-> from ( ' users ' )-> where ( ' city ' , ' = ' , ' Berlin ' )
-> andWhere ( ' age ' , ' > ' , ' 20 ' )-> getAll ();
$ result = App:: Query ()-> select ()-> from ( ' users ' )-> where ( ' city ' , ' = ' , ' Berlin ' )
-> orWhere ( ' city ' , ' = ' , ' Paris ' )-> getAll ();
$ result = App:: Query ()-> select ()-> from ( ' users ' )-> orderBy ( ' age ' , ' DESC ' )
-> limit ( 25 )
-> offset ( 50 )-> getAll ();
//INSERT Query:
$ affectedRows = App:: Query ()-> insertInto ( ' users ' )-> values ([ " username " => " jameshetfield " ,
" password " => " 19831983 " ,
" city " => " Downey " ])-> execute (); 결과를 반환하지 않는 쿼리 는 php execute() 사용하여 실행해야하며 영향을받는 행의 수를 자동으로 반환합니다.
//UPDATE Query:
$ affectedRows = App:: Query ()-> update ( ' users ' )-> set ([ " age " => 53 ,
" band " => " Metallica " ])
-> where ( ' username ' , ' = ' , ' jameshetfield ' )-> execute ();
//DELETE Query:
$ affectedRows = App:: Query ()-> deleteFrom ( ' users ' )-> where ( ' username ' , ' = ' , ' someone ' )-> execute ();삭제 또는 업데이트 쿼리 는 보안 조치로 제공된 위치가없는 경우 데이터가 손실 될 수 있습니다. 연결 클래스를 수동으로 사용하여 이러한 쿼리를 실행하십시오.
레이어 3- 객체 관계 매핑 : ORM은 다음 섹션에서 논의됩니다.
Wikipedia에 따르면 :
ORM (Object-Relational Mapping)은 객체 지향 프로그래밍 언어에서 호환되지 않는 유형 시스템간에 데이터를 변환하는 프로그래밍 기술입니다. 사실상 프로그래밍 언어 내에서 사용할 수있는 "가상 객체 데이터베이스"가 생성됩니다.
Dejframework는 MVC 아키텍처에서 작동하기 때문에 데이터 지속성은 MVC의 모델 구성 요소에 포함됩니다. 모델은 쇼핑 시스템에서 사용자, 구매, 제품 등과 같은 응용 프로그램의 엔터티와 관련이 있습니다. 그들은 데이터베이스를 오가서 저장하고 검색해야합니다. 관계형 데이터베이스는 SQL 언어로 작동하며 대부분의 프레임 워크가 객체 지향 환경에서 작동하는 것처럼 Dejframework. PHP 코드 중간에있는 SQL 코드는 최고 실습이 아닌 것으로 간주됩니다. 따라서 Dejframework는 SQL 코드에서 3 레벨로 분리하려고 시도하고, 그 중 2 개는 이전 섹션에서 정교 해졌으며 이제 모델로 작업하는 방법을 볼 수 있습니다.
class User extends dej mvc Model
{
protected static $ dbTable = " users " ;
//Format: ["db_field_name" => "modelPropertyName"]
protected static $ primaryKey = [ " id " => " id " ];
//Model properties
public $ username ;
public $ password ;
public $ city ;
.
.
.
} class User extends dej mvc Model
{
protected static $ dbTable = " users " ;
//Format: ["db_field_name" => "modelPropertyName"]
protected static $ dbFields = [ " username " => " username " ,
" password " => " password " ,
" city " => " city " ,
" id " => " id " ];
public $ username ;
public $ password ;
public $ city ;
.
.
.
} id 속성 은 모델이 확장되는 /dej/mvc/Model 클래스에 정의됩니다. 따라서 모델에 ID를 갖기를 원한다면 다시 정의 할 필요가 없습니다.
class User extends dej mvc Model
{
protected static $ dbTable = " users " ;
protected static $ dbFields = [ " username " => " username " ,
" password " => " password " ,
" city " => " city " ,
" id " => " id " ];
//Exactly the same as the class name
protected static $ modelName = " User " ;
public $ username ;
public $ password ;
public $ city ;
.
.
.
}이 구성을 올바르게 설정 한 경우 모델에서 ORM 메소드를 사용할 수 있습니다. 아래 예제를 살펴보십시오.
//Creating a new record
use app models User ;
$ user = new User ();
$ user -> username = " jameshetfield " ;
$ user -> password = " 13831383 " ;
$ user -> city = " Downey " ;
$ user -> create (); //Saved into the database.
//or you can set the properties in the constructor
$ user = new User ([
' username ' => ' jameshetfield ' ,
' password ' => ' 13831383 ' ,
' city ' => ' Downey '
]);
$ user -> create ();ORM은 아래에 Dej 쿼리 빌더를 사용하여 필요한 쿼리를 생성합니다.
Create (), update () 및 delete () 반환 에 영향을받는 행을 반환하여 작업이 성공했는지 확인할 수 있습니다.
//Finding a record by a field named 'id'
$ user = User:: findById ( 11 );
//changing it's properties
$ user -> password = " through_the_never " ;
$ user -> update (); //Updated in the database.
//deleting it.
$ user -> delete ();이러한 기능은 기본 레코드 키와 함께 작동합니다.
//Finding records by some condition.
$ users = User:: find ()-> where ( ' city ' , ' = ' , ' Sari ' )-> getAll (); //Returns an array of User objects.
//A more complex one
$ users = User:: find ()-> where ( ' city ' , ' = ' , ' Sari ' )-> andWhere ( ' age ' , ' > ' , 20 )-> orderBy ( ' age ' , ' ASC ' )
-> limit ( 25 )
-> offset ( 100 )-> getAll ();
//Don't forget the get*() method!
//Retrieveing all records
$ users = User:: getAll (); //doesn't need a getAll() at the end because it knows what to do.
//The method for deleting by condition is named 'wipe'
$ users = User:: wipe ()-> where ( ' status ' , ' = ' , ' banned ' )-> orWhere ( ' email_confirmation ' , ' = ' , ' 0 ' )-> execute ();
//counting all records
$ userCount = User:: countAll ();
//counting records that have a certain condition
$ userCount = User:: count ()-> where ( ' city ' , ' = ' , ' Sari ' )-> getInt (); //getInt() returns the count of the results as an Integer. dejframework의 데이터 유효성 검사는 dejValidator 클래스에서 처리합니다. 다양한 방법으로 사용할 수 있습니다.
App::Validator() 사용하여 싱글 톤 인스턴스를 제공하는 유효성 검사 서비스를 사용할 수 있습니다. 2 매개 변수 : 검증 할 값을 허용합니다. (문자열, int, 배열, 객체) 및 데이터에 대한 검증을위한 일련의 규칙 .그것이 어떻게 작동하는지 보자 :
use dej App ;
//Validate a single value according to a set of rules seperated by "|".
$ result = App:: Validator ()-> validate ( " This is going to be validated " , " required|string|min:5|max:30 " );
//Validate an object or and array:
$ result = App:: Validator ()-> validate ( $ user , [ ' username ' => ' required|string|email|min:5|max:30 ' ,
' password ' => ' required|string|min:10|max:100 ' ],
' age ' => ' int|min:18|max:99 ' ); validate() 메소드는 배열을 반환합니다. 유효성 검사 오류가없고 데이터가 유효한 경우 빈 배열이됩니다. 따라서 데이터가 empty() 로 유효한지 확인할 수 있습니다. 유효성 검사 오류가 있으면 배열에 표시됩니다.
//The rules have changed
$ errors = App:: Validator ()-> validate ( " This is going to be validated " , " required|string|email|min:5|max:10 " );
var_dump ( $ errors );이것이 위의 코드가 출력하는 것입니다.
array
0 => 'This Field should be an email'
1 => 'This Field should be less than 10'
이제 물체와 함께 :
$ errors = App:: Validator ()-> validate ( $ obj , [ ' email ' => ' required|string|email ' ,
' password ' => ' required|string ' ,
' age ' => ' int ' ]);
var_dump ( $ errors );산출:
array (size=3)
'email' =>
array (size=1)
0 => string 'This Field should be an email'
'password' =>
array (size=2)
0 => string 'This Field is Required'
1 => string 'This Field should be more than 10'
'age' =>
array (size=1)
0 => string 'This Field should be a number'
보시다시피, 객체 나 배열을 유효성 검사기에 전달하면 키가 필드 이름이고 해당 필드와 관련된 오류가 포함 된 값이 포함 된 연관 배열에서 각 필드와 관련된 오류를 반환합니다.
validate() 메소드를 사용하여 요청 매개 변수 (get & post 매개 변수)를 검증 할 수 있습니다. $ errors = App:: Request ()-> validate ([ ' email ' => ' required|string|email ' ,
' password ' => ' required|string|min:10|max:100 ' ]);
var_dump ( $ errors ); yoursite.local/?email=notanemail&password=123 방문하면 다음과 같습니다.
array (size=2)
'email' =>
array (size=1)
0 => string 'This Field should be an email'
'password' =>
array (size=1)
0 => string 'This Field should be more than 10'
/app/models/User.php 에 포함 된 사용자 모델을 참조하십시오. class User extends dej mvc Model
{
.
.
.
protected static $ validationRules = [ " username " => " required|string|min:5|max:20 " ,
" password " => " required|string|min:5|max:255 " ,
" city " => " string|max:10 " ];
.
.
.
}이제 모델의 인스턴스를 검증 할 수 있습니다.
$ user = User:: getById ( 11 );
$ errors = $ user -> validate (); //returns errors in array like the previous examples.
$ isValid = $ user -> isValid (); //returns true or false당신이 당신의 오류가 있으면, 당신은 그것을 표시하기 위해보기에 전달하거나 그들과 함께 어딘가에 리디렉션 할 수 있습니다.
//in the controller
$ errors = $ user -> validate ();
if (! empty ( $ errors )) return App:: Response ()-> redirect ( ' / ' )-> withErrors ( $ errors ); 이전 예제에서 보았던 유효성 검사 메시지는 기본 메시지였습니다. 변경하려면 어떻게 또는 자신의 언어로 유효성 검사 메시지가 있습니까? /app/locale/en/validation/messages.php 를 살펴보십시오.
return [
" required " => " This Field is Required " ,
" string " => " This Field should be an string " ,
" int " => " This Field should be a number " ,
" min " => " This Field should be more than %s " ,
" max " => " This Field should be less than %s " ,
" email " => " This Field should be an email " ,
]; 키가 유효성 검사 유형에 해당하고 값이 유효성 검사 메시지임을 알 수 있습니다. 변수는 's'가있는 메시지에 포함됩니다. /app/locale 에서 선택한 언어에 대한 자신의 디렉토리를 만들 수 있으며 해당 디렉토리에는 변수가 포함 된 고유 한 유효성 검사 메시지가 있습니다.
/config.json 에서 기본 로케일을 설정할 수 있습니다.
App::Config()->locale = 'your_locale';
PHP 세션에서 작업하기 위해 Dejframework는 dejSession 클래스를 제공합니다. 다음은 사용 방법에 대한 몇 가지 예입니다.
//to set session variables
App:: Session ()-> save ([
' key1 ' => ' value1 ' ,
' key2 ' => ' value2 '
]);
//to get session variables
$ value1 = App:: Session ()-> get ( ' key1 ' );
//to regenerate session id
App:: session ()-> regenerateId ();
//get all session variables as associative array
$ wholeSession = App:: session ()-> all ();
//destroy the session
App:: session ()-> destroy ();
//delete a variable
App:: session ()-> delete ( ' key1 ' );
//see if variable is set
$ trueOrFalse = App:: session ()-> isSaved ( ' key1 ' );예를 들어 특정 오류 메시지와 같은 세션 변수를 다음 요청에서만 사용할 수있게하려면 다음과 같은 세션으로 플래시 할 수 있습니다.
App:: session ()-> flash ([ ' message ' => ' Registered Successfully! ' ]);다음 요청에서 검색하십시오.
$ message = App:: session ()-> getFlash ( ' message ' ); 플래시 메시지는 다음 요청에서만 사용할 수 있으며 ->getFlash() 에서만 사용할 수 있습니다.
세션에 마지막으로 액세스 한 이후 정의 된 시간 후에 세션이 만료되도록 설정할 수 있습니다.
App:: Session ()-> save ([ ' key ' => ' value ' ]);
App:: Session ()-> lifeTime ( 60 ); //session will expire after 60 seconds since last access to the session. (last use of App::Session())때로는 응용 프로그램이 다음 요청에 대한 모델 인스턴스를 기억하기를 원할 수도 있습니다. 예를 들어, 앱이 로그인 한 사용자 또는 사용자가 가진 쇼핑 카트 또는 다른 항목을 기억하기를 원합니다. 세션에서 원하는 모델의 기본 키를 저장하고 모든 요청에서 쿼리를 실행하면 지루할 수 있습니다. Dejframework는 모델에서 사용할 수있는 특성을 제공하여이를 해결합니다. 봐 :
class ShoppingCart extends dej mvc Model
{
use dej traits IsStateful;
.
.
.
}이제 모델에서 몇 가지 더 많은 방법을 사용할 수 있습니다.
//suppose you want to create a shopping cart for a guest user and add a product to it:
$ cart = new ShoppingCart ();
$ cart -> addProduct ( 2389 );
$ cart -> create (); //stored in the db
//if you want to save it to the session get it easily in the next request
$ cart -> remember ( ' guest_shopping_cart ' ); //provide a key to remember it by this key.이제 다음 요청에서 :
if (ShoppingCart:: isRemembered ( ' guest_shopping_cart ' )) //see if theres any cart in the session
$ cart = ShoppingCart:: retrieve ( ' users_shopping_cart ' ); //get's fresh data from the db
if (ShoppingCart:: hasChanged ( ' guest_shopping_cart ' ))
{
//checks if the cart in the database has changed **since you saved the cart in the session**.
doSomeThing ();
}
ShoppingCart:: forget ( ' guest_shopping_cart ' ); //forgets the cart. 데이터를 사용자에게 제시하려면 사용자 인터페이스가 필요합니다. 웹에서 대부분의 경우 이것은 HTML 마크 업을 의미합니다. MVC에서 논리는 UI에서 분리되어야하므로 HTML을 뷰에 넣고 값을 echo 하거나 배열을 반복하기 위해 배열에 배열을 넣는 것과 같은 프리젠 테이션 로직 만 포함시켜야합니다. 보기를 만들려면 :
/app/views 에서보기 파일을 만듭니다. 기본적으로 뷰가 포함되어 있습니다 : index.phtml <!DOCTYPE html >
< html >
< head >
< title > < ?= $data- > user- > username ? > 's profile </ title >
</ head >
< body >
< h2 > View < ?= $data- > user- > username ? > 's Profile </ h2 >
< p > Username: < ?= $data- > user- > username ? > </ p >
< p > Password: < ?= $data- > user- > password ? > </ p >
< p > City: < ?= $data- > user- > city ? > </ p >
</ body >
</ html > class IndexController extends dej mvc Controller
{
public static function index()
{
$ user = User:: find ()-> where ( ' username ' , ' = ' , ' jameshetfield ' )-> getOne ();
return App:: View ( ' user ' , [ ' user ' => $ user ]); //the first argument is the view name,
the second one is the data you want to pass to
the view, in this example, a variable called ' user '
will be available in the user.phtml view
which contains the instance of user we fetched.
Piece of cake!
}
}오류 메시지도 제공 할 수 있습니다.
//in the controller
return App:: View ( ' user ' )-> withErrors ([ ' authorization ' => ' You are not allowed to view this user. ' ]);프레임 워크는 뷰를 출력으로 만들고 결과는 다음과 같습니다.
<!DOCTYPE html >
< html >
< head >
< title > jameshetfield's profile </ title >
</ head >
< body >
<!-- access the errors like this: -->
< span class =" error " > < ?= $this- > errors('authorization') ? > </ span >
< h2 > View jameshetfield's Profile </ h2 >
< p > Username: jameshetfield </ p >
< p > Password: 13831383 </ p >
< p > City: Downey </ p >
</ body >
</ html >이제 또 다른 예를 보자. 모든 사용자의 테이블을 만들려면 어떻게해야합니까? 견해 편집 :
<!DOCTYPE html >
< html >
< head >
< title > All Users </ title >
</ head >
< body >
< table >
< tr >
< th > username </ th >
< th > password </ th >
< th > city </ th >
</ tr >
< ?php foreach ($data- > users as $user): ? >
< tr >
< th > < ?= $user- > username ? > </ th >
< th > < ?= $user- > password ? > </ th >
< th > < ?= $user- > city ? > </ th >
</ tr >
< ?php endforeach; ? >
</ table >
</ body >
</ html >그리고 컨트롤러 :
class IndexController extends dej mvc Controller
{
public static function index ()
{
$ users = User:: getAll ();
return App:: View ( ' user ' , [ ' users ' => $ users ]);
}
}그리고 자신을위한 결과를보십시오!
부분적으로보기를 생성하고 다른 뷰에서 붙여 넣을 수 있습니다.
[/app/views/partials/header.phtml]
<!--begin header-->
<!DOCTYPE html >
< html >
< head >
< meta charset =" UTF-8 " >
< title > < ?= $data- > title ? > </ title >
</ head >
< body >
<!--end header--> index.phtml 에 붙여 넣습니다.
[/app/views/index.phtml]
< ?php $this- > paste('partials/header'); ? >
< h2 > < ?= $data- > message ? > </ h2 >
.
.
.
</ html > 인증은 응용 프로그램 관련 문제입니다. 모든 애플리케이션에서는 매우 차이가 될 수 있으므로 Dejframework는 프레임 워크 자체에서이를 구현하지 않으며 대신 인증이 발생하는 기본 사용자 모델, 인증 경로 및 컨트롤러 로직이 제공되며이를 변경하거나 자신의 솔루션을 자유롭게 변경할 수 있으며 프레임 워크에서 구현되는 솔루션을 사용하여 사용자 모델에서 IsStateful FRATIT를 사용하여 ()를 사용하여 $user->remember() 사용하여 ()를 사용합니다. 당신이해야 할 유일한 것은 config.json 에서 'default_auth_model' 설정하여 App::Request->user() to ::retrieve() 를 사용하여 IsStateful TRAIT를 사용하여 세션에서 사용자를 사용할 수 있도록하는 것입니다.
인증을 이해하기 위해 프레임 워크에서 제공되는 컨트롤러, 모델 및보기를 살펴보십시오. 그리고 원하는대로 변경/개선/제거하십시오.
참고 : 사용자 모델이 올바르게 작동하려면 2 개의 필드가있는 users 라는 테이블을 만들어야합니다.
TABLE: users
FIELD TYPE
id int, autoincrement
username varchar
password varchar(255) //password hashing system requires 255