Kerangka kerja php mvc ringan
composer install php >= 5.6 composer
Ini didukung oleh blade, beberapa bantuan di sini: https: //laravel.com/docs/5.3/blade
$ this -> render ( ' your/blade ' , array ( ' your ' => ' variables ' ));Pastikan Anda memiliki root akses yang tepat dari proyek.
chmod -R 0755 /Path/to/Longphp
chmod -R 0644 /Path/to/Longphp/cache
chmod -R 0644 /Path/to/Longphp/Application/logsSetelah menulis perpustakaan/pengontrol Anda sendiri (dll), pastikan Anda telah menjalankan perintah ini:
composer dump-autoloadLongPHP ditenagai oleh komposer, yang dapat membantu Anda memperluas aplikasi dengan menggunakan namespace.
Democontroller
<?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 ' );
}
}Anda bisa mendapatkan akses ke metode indeks seperti ini: http: //yourhost/index.php/demo/index
Konfigurasikan database Anda di Application/config/database.php
| konfigurasi | opsi | keterangan |
|---|---|---|
db_host | Nama Host Basis Data | |
db_user | Nama Pengguna Basis Data | |
db_password | Lulus basis data | |
db_port | 3306/(Lainnya) | Port database |
db_database | Basis Data Basis Data | |
db_charset | UTF8/(Lainnya) | Charset Basis Data |
db_driver | mysqli | Driver basis data, hanya mySQL yang didukung sekarang |
Model demo:
<?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 ();
}
} Ketika Anda tidak mengetahui pengontrol atau metode dalam URL, Anda dapat mengatur pengontrol dan metode default Anda di Application/config/router.php dan menggunakan sebagai default.
| konfigurasi | keterangan |
|---|---|
default_controller | Pengontrol default |
default_method | Metode default |
Mendapatkan data input.
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 memberikan dukungan sesi. Dukungan untuk Driver Sesi Sekarang: file , database .
File konfigurasi disimpan di Application/config/config.php
| konfigurasi | opsi | keterangan |
|---|---|---|
session_driver | file/database | Tempat menyimpan sesi |
session_path | Kerangka kerja/sesi | Lokasi File Sesi. Biarkan kosong untuk menggunakan default |
session_cookie_name | Toko token sesi di browser | |
session_expiration | 7200/(waktu yang Anda inginkan) | Waktu kedaluwarsa sesi |
Anda dapat menggunakan LongSession::get($key) untuk mengambil data. LongSession::all() untuk mengambil semua data yang telah Anda masukkan.
Pastikan bahwa Anda telah menggunakan 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
}
} Menggunakan metode set dapat membantu Anda memasukkan data ke dalam sesi. Jika Anda bersedia meletakkan banyak data, batchSet akan berguna.
//put data
LongSession:: set ( ' key ' , ' value ' );
//batch assignment
LongSession:: batchSet ([ ' test1 ' => ' data1 ' , ' test2 ' => ' data2 ' ]); Metode remove akan menghapus sepotong data dari sesi. Jika Anda ingin mendapatkan data sebelum menghapusnya, gunakan pull . Jika Anda ingin menghapus semua data dari sesi, Anda dapat menggunakan metode flush :
//delete 'key'
LongSession:: remove ( ' key ' );
//get 'key' then delete it
LongSession:: pull ( ' key ' );
//Delete all data
LongSession:: flush ();Regenerasi ID sesi sering dilakukan untuk mencegah pengguna jahat mengeksploitasi serangan fiksasi sesi pada aplikasi Anda.
LongPHP secara otomatis meregenerasi ID sesi; Namun, jika Anda perlu meregenerasi ID sesi secara manual, Anda dapat menggunakan metode regenerasi.
LongPHP:: regenerate ();Cookie Opertations:
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 ' );Tingkat logger:
const EMERGENCY = ' emergency ' ;
const ALERT = ' alert ' ;
const CRITICAL = ' critical ' ;
const ERROR = ' error ' ;
const WARNING = ' warning ' ;
const NOTICE = ' notice ' ;
const INFO = ' info ' ;
const DEBUG = ' debug ' ; Anda dapat menelepon metode logging sesuai dengan log level
| konfigurasi | opsi | keterangan |
|---|---|---|
log_level | 0/1/2/3/4 | Level log |
log_path | Di mana menyimpan file log. |
0 Jangan lakukan log 1 Log Only Error 2 Log Error 、 Peringatan 、 PEMBERITAHUAN 3 ERROR 、 PERINGATAN 、 PEMBERITAHUAN 、 INFO 4 LOG ALL
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 callingPenggunaan
Asumsikan file diunggah dengan formulir HTML ini:
< form method =" POST " enctype =" multipart/form-data " >
< input type =" file " name =" foo " value ="" />
< input type =" submit " value =" Upload File " />
</ form >Ketika formulir HTML dikirimkan, kode PHP sisi server dapat memvalidasi dan mengunggah file seperti ini:
<?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 ();
} Jika Anda ingin membuat URI Anda lebih pendek, url rewrite akan membantu Anda menyembunyikan index.php di URI.
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 ;
}Jika proyek Anda bukan direktori root
Misalnya, proyek Anda terletak di /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 ;
} Jika Anda menantikan untuk menulis ulang URL, pastikan bahwa Anda telah mengaktifkan Apache rewrite module . Kami telah menulis file .htaccess di bawah direktori kerangka kerja untuk Anda.
Berikut adalah konfigurasi 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>