가벼운 PHP MVC 프레임 워크
composer install php >= 5.6 composer
이것은 Blade로 구동됩니다. 여기에는 https : //laravel.com/docs/5.3/blade가 있습니다
$ this -> render ( ' your/blade ' , array ( ' your ' => ' variables ' ));프로젝트의 올바른 액세스 루트가 있는지 확인하십시오.
chmod -R 0755 /Path/to/Longphp
chmod -R 0644 /Path/to/Longphp/cache
chmod -R 0644 /Path/to/Longphp/Application/logs자신의 라이브러리/컨트롤러 (등)를 작성한 후이 명령을 실행했는지 확인하십시오.
composer dump-autoloadLongphp는 Composer가 구동하여 네임 스페이스를 사용하여 응용 프로그램을 확장하는 데 도움이됩니다.
데모 컨트롤러
<?php
/**
* Longphp
* Author: William Jiang
*/
namespace Application Controller ;
use Long Core Config ;
use Long Core LongException ;
use Long Library Input ;
use Long Core LongController ;
use Long Library Logger Log ;
use Long Library Session LongSession ;
use Long Library Url ;
class DemoController extends LongController
{
//construct method
public function initialize (){
$ this -> _output ( " initMethod<br> " );
}
public function index ()
{
echo Input:: get ( ' a ' );
echo " index method called<br> " ;
}
public function testRender ()
{
$ this -> _render ( ' test ' , [ ' test ' => ' test here ' ]);
}
protected function testConfig ()
{
print_r (Config:: get ());
}
public function testOutput ()
{
$ this -> _output ([ ' testdata1 ' => ' data1 ' , ' testdata2 ' => ' data2 ' ], ' json ' );
//$this->_output('raw data test<br>' . PHP_EOL, 'raw');
}
public function testUrl ()
{
$ this -> _output (Url:: siteUrl ( ' https ' ) . PHP_EOL , ' raw ' );
}
protected function testError ()
{
//测试捕获异常
new EmptyClass ();
}
protected function testException ()
{
//测试Exception
throw new LongException ( ' Test Exception ' );
}
public function testModel ()
{
$ model = $ this -> _model ( ' testModel ' );
print_r ( $ model -> getById ( 4 ));
var_dump ( $ model -> insertTestData ());
var_dump ( $ model -> deleteTestData ( 2 ));
var_dump ( $ model -> updateTestData ( 1 , '测试' ));
var_dump ( $ model -> transTestData ());
}
public function testLogger (){
Log:: warning ( " test warning " );
}
public function testSession (){
LongSession:: set ( ' test_data ' , 123 );
$ data = LongSession:: get ( ' test_data ' );
var_dump ( $ data );
//LongSession::destroy();
LongSession:: batchSet ([ ' test1 ' => ' data1 ' , ' test2 ' => ' data2 ' ]);
var_dump (LongSession:: all ());
echo ' <br/> ' ;
var_dump (LongSession:: pull ( ' test1 ' ));
LongSession:: remove ( ' test2 ' );
}
}http : //yourhost/index.php/demo/index와 같은 색인 메소드에 액세스 할 수 있습니다.
Application/config/database.php 에서 데이터베이스를 구성하십시오
| 구성 | 옵션 | 설명 |
|---|---|---|
db_host | 데이터베이스 호스트 이름 | |
db_user | 데이터베이스 사용자 이름 | |
db_password | 데이터베이스 패스 | |
db_port | 3306/(기타) | 데이터베이스 포트 |
db_database | 데이터베이스 데이터베이스 | |
db_charset | UTF8/(기타) | 데이터베이스 charset |
db_driver | mysqli | 데이터베이스 드라이버, 이제 MySQL 만 지원됩니다 |
데모 모델 :
<?php
/**
* Longphp
* Author: William Jiang
*/
namespace Application Model ;
use Long Core LongModel ;
class TestModel extends LongModel
{
public function getById ( $ id = 1 )
{
return $ this -> db -> query ( ' SELECT * FROM test_table WHERE id = ? ' , array ( $ id ));
}
public function insertTestData ()
{
return $ this -> db -> query ( ' INSERT INTO test_table(`number`,`doubled`,`strings`,`time`) VALUES(?,?,?,?) ' , [ 1 , 1.111 , ' string test ' , date ( ' Y-m-d H:i:s ' )]);
}
public function updateTestData ( $ id = 1 , $ update )
{
return $ this -> db -> query ( ' UPDATE test_table SET `strings` = ? WHERE `id` = ? ' , array ( $ update , $ id ));
}
public function deleteTestData ( $ id = 1 )
{
return $ this -> db -> query ( ' DELETE FROM test_table WHERE id = ? ' , array ( $ id ));
}
public function transTestData (){
$ this -> db -> transStart ();
$ this -> updateTestData ( 1 , ' This is Transaction ' );
$ this -> db -> commit ();
$ this -> db -> transStart ();
$ this -> updateTestData ( 1 , ' This is rollback ' );
$ this -> db -> rollback ();
}
} URL에서 컨트롤러 또는 메소드를 파악하지 못하면 Application/config/router.php 에서 기본 컨트롤러 및 메소드를 설정하고 기본값으로 사용할 수 있습니다.
| 구성 | 설명 |
|---|---|
default_controller | 기본 컨트롤러 |
default_method | 기본 방법 |
입력 데이터를 얻습니다.
use Long Library Input ; //import Input
. . .
//getting input data
echo Input:: get ( ' key ' );
echo Input:: post ( ' key ' );
echo Input:: put ( ' key ' );
echo Input:: delete ( ' key ' ); Longphp는 세션 지원을 제공합니다. 지금 세션 드라이버 지원 : file , database .
구성 파일은 Application/config/config.php 에 저장됩니다
| 구성 | 옵션 | 설명 |
|---|---|---|
session_driver | 파일/데이터베이스 | 세션을 저장할 곳 |
session_path | 프레임 워크/세션 | 세션 파일 위치. 기본값을 사용하려면 비워 두십시오 |
session_cookie_name | 브라우저의 세션 토큰 저장소 | |
session_expiration | 7200/(원하는 시간) | 세션의 만료 시간 |
LongSession::get($key) 사용하여 데이터를 검색 할 수 있습니다. LongSession::all() 가 넣은 모든 데이터를 검색합니다.
네임 스페이스 LongLibrarySession 사용했는지 확인하십시오
namespace Application Controller ;
use Long Library Session ;
class UserController extends LongController
{
public function show ()
{
$ value = LongSession:: get ( ' key ' );
//if you want to get all data
}
} set 방법을 사용하면 데이터를 세션에 넣는 데 도움이 될 수 있습니다. 많은 데이터를 기꺼이 넣으려면 batchSet 유용합니다.
//put data
LongSession:: set ( ' key ' , ' value ' );
//batch assignment
LongSession:: batchSet ([ ' test1 ' => ' data1 ' , ' test2 ' => ' data2 ' ]); remove 메소드는 세션에서 데이터 조각을 제거합니다. 데이터를 제거하기 전에 데이터를 얻으려면 pull 사용하십시오. 세션에서 모든 데이터를 제거하려면 flush 메소드를 사용할 수 있습니다.
//delete 'key'
LongSession:: remove ( ' key ' );
//get 'key' then delete it
LongSession:: pull ( ' key ' );
//Delete all data
LongSession:: flush ();악의적 인 사용자가 응용 프로그램에서 세션 고정 공격을 악용하지 않도록 세션 ID를 재생하는 경우가 종종 있습니다.
Longphp는 세션 ID를 자동으로 재생합니다. 그러나 세션 ID를 수동으로 재생 해야하는 경우 재생 메소드를 사용할 수 있습니다.
LongPHP:: regenerate ();쿠키 오염 :
use Long Library Cookie
...
//retrive cookie
echo Cookie:: get ( ' test_cookie ' );
//set cookie
Cookie:: set ( ' test_cookie ' , ' cookie value ' , 100 );
//remove cookie
Cookie:: remove ( ' test_cookie ' );로거의 레벨 :
const EMERGENCY = ' emergency ' ;
const ALERT = ' alert ' ;
const CRITICAL = ' critical ' ;
const ERROR = ' error ' ;
const WARNING = ' warning ' ;
const NOTICE = ' notice ' ;
const INFO = ' info ' ;
const DEBUG = ' debug ' ; log level 에 따라 로깅 방법을 호출 할 수 있습니다.
| 구성 | 옵션 | 설명 |
|---|---|---|
log_level | 0/1/2/3/4 | 로그 레벨 |
log_path | 로그 파일을 저장할 위치. |
0 로그를 수행하지 않음 1 로그 전용 오류 2 로그 오류 、 경고 、 경고 3 오류 、 경고 、 통지 4 로그
use Long Library Logger Log ; //to import logger
. . . .
Logger:: debug ( " some debug message " ); // static calling
Logger:: info ( " some info message " ); // static calling
Logger:: warning ( " some warning message " ); // static calling
Logger:: notice ( " some notice message " ); // static calling
Logger:: error ( " some error message " ); // static calling
Logger:: critical ( " some critical message " ); // static calling
Logger:: alert ( " some alert message " ); // static calling
Logger:: emergency ( " some emergency message " ); // static calling용법
파일 이이 HTML 양식으로 업로드되었다고 가정합니다.
< form method =" POST " enctype =" multipart/form-data " >
< input type =" file " name =" foo " value ="" />
< input type =" submit " value =" Upload File " />
</ form >HTML 양식이 제출되면 서버 측 PHP 코드는 다음과 같은 파일을 유효성있게 유효성있게 업로드 할 수 있습니다.
<?php
$ storage = new Upload Storage FileSystem ( ' /path/to/directory ' );
$ file = new Upload File ( ' foo ' , $ storage );
// Optionally you can rename the file on upload
$ new_filename = uniqid ();
$ file -> setName ( $ new_filename );
// Validate file upload
// MimeType List => http://www.iana.org/assignments/media-types/media-types.xhtml
$ file -> addValidations ( array (
// Ensure file is of type "image/png"
new Upload Validation Mimetype ( ' image/png ' ),
//You can also add multi mimetype validation
//new UploadValidationMimetype(array('image/png', 'image/gif'))
// Ensure file is no larger than 5M (use "B", "K", M", or "G")
new Upload Validation Size ( ' 5M ' )
));
// Access data about the file that has been uploaded
$ data = array (
' name ' => $ file -> getNameWithExtension (),
' extension ' => $ file -> getExtension (),
' mime ' => $ file -> getMimetype (),
' size ' => $ file -> getSize (),
' md5 ' => $ file -> getMd5 (),
' dimensions ' => $ file -> getDimensions ()
);
// Try to upload file
try {
// Success!
$ file -> upload ();
} catch ( Exception $ e ) {
// Fail!
$ errors = $ file -> getErrors ();
} URI를 짧게 만들려면 url rewrite URI에서 index.php 숨기는 데 도움이됩니다.
server
{
listen 80 ;
server_name www.example.com ;
index index.shtml index.html index.htm index.php ;
root /path/to/root/Longphp ;
location / {
try_files $uri $uri / =404 ;
if ( ! -e $request_filename )
{
rewrite (. * ) /index.php ;
}
}
location ~ . * . (php | php5) ? $
{
fastcgi_pass 127.0.0.1:9000 ;
fastcgi_index index.php ;
include fastcgi.conf ;
}
access_log /var/log/Longphp/access.log access ;
}프로젝트가 루트 디렉토리가 아닌 경우
예를 들어, 프로젝트는 /path/to/root/Longphp 에 있습니다
server
{
listen 80 ;
server_name www.example.com ;
index index.shtml index.html index.htm index.php ;
root /path/to/root ;
location /Longphp {
try_files $uri $uri / =404 ;
if ( ! -e $request_filename )
{
rewrite (. * ) /Longphp/index.php ;
}
}
location ~ . * . (php | php5) ? $
{
fastcgi_pass 127.0.0.1:9000 ;
fastcgi_index index.php ;
include fastcgi.conf ;
}
access_log /var/log/Longphp/access.log access ;
} URL을 다시 쓰기를 기대하는 경우 Apache rewrite module 활성화했는지 확인하십시오. 우리는 이미 Framework Directory 아래에 .htaccess 파일을 작성했습니다.
다음은 Apache의 구성입니다.
<VirtualHost *:80>
DocumentRoot "/path/to/Longphp"
ServerName www.example.com
AddType application/x-httpd-php .php
<Directory />
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
DirectoryIndex index.php
</Directory>
</VirtualHost>