Un marco Light PHP MVC
composer install php >= 5.6 composer
Esto funciona con Blade, algo de ayuda aquí: https: //laravel.com/docs/5.3/blade
$ this -> render ( ' your/blade ' , array ( ' your ' => ' variables ' ));Asegúrese de tener la raíz de acceso correcta del proyecto.
chmod -R 0755 /Path/to/Longphp
chmod -R 0644 /Path/to/Longphp/cache
chmod -R 0644 /Path/to/Longphp/Application/logsDespués de escribir su propia biblioteca/controlador (etc.), asegúrese de haber ejecutado este comando:
composer dump-autoloadLongPhp funciona con compositor, que puede ayudarlo a extender su aplicación mediante el espacio de nombres.
Democontrolador
<?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 ' );
}
}Puede obtener acceso al método de índice como este: http: //yourhost/index.php/demo/index
Configurar su base de datos en Application/config/database.php
| configuración | opción | descripción |
|---|---|---|
db_host | Nombre de host de base de datos | |
db_user | Nombre de usuario de la base de datos | |
db_password | Pase de base de datos | |
db_port | 3306/(otros) | Puerto de base de datos |
db_database | Base de datos de la base de datos | |
db_charset | utf8/(otros) | Charlatán de la base de datos |
db_driver | mysqli | Controlador de bases de datos, solo MySQL es compatible ahora |
Modelo de demostración:
<?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 ();
}
} Cuando no descubre el controlador o el método en URL, puede establecer su controlador y método predeterminado en Application/config/router.php y usar como predeterminado.
| configuración | descripción |
|---|---|
default_controller | Controlador predeterminado |
default_method | Método predeterminado |
Obtener datos de entrada.
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 proporciona soporte de sesión. Soporte para el controlador de sesión ahora: file , database .
El archivo de configuración se almacena en Application/config/config.php
| configuración | opción | descripción |
|---|---|---|
session_driver | Archivo/base de datos | Dónde almacenar sesión |
session_path | Marco/sesión | Ubicación de archivos de sesión. Deja en blanco para usar el valor predeterminado |
session_cookie_name | La tienda de tokens de sesión en el navegador | |
session_expiration | 7200/(tiempo que quieres) | El tiempo de vencimiento de la sesión |
Puede usar LongSession::get($key) para recuperar datos. LongSession::all() para recuperar todos los datos que ha puesto.
Asegúrese de haber usado el espacio de nombres 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
}
} El uso del método set puede ayudarlo a poner los datos en sesión. Si está dispuesto a poner un montón de datos, batchSet será útil.
//put data
LongSession:: set ( ' key ' , ' value ' );
//batch assignment
LongSession:: batchSet ([ ' test1 ' => ' data1 ' , ' test2 ' => ' data2 ' ]); El método remove eliminará una pieza de datos de la sesión. Si desea obtener los datos antes de eliminarlos, use pull . Si desea eliminar todos los datos de la sesión, puede usar el método flush :
//delete 'key'
LongSession:: remove ( ' key ' );
//get 'key' then delete it
LongSession:: pull ( ' key ' );
//Delete all data
LongSession:: flush ();La regeneración de la ID de sesión a menudo se realiza para evitar que los usuarios maliciosos exploten un ataque de fijación de sesión en su aplicación.
LongPhp regenera automáticamente la ID de sesión; Sin embargo, si necesita regenerar manualmente la ID de sesión, puede usar el método de regeneración.
LongPHP:: regenerate ();Operaciones de cookies:
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 ' );Los niveles de registrador:
const EMERGENCY = ' emergency ' ;
const ALERT = ' alert ' ;
const CRITICAL = ' critical ' ;
const ERROR = ' error ' ;
const WARNING = ' warning ' ;
const NOTICE = ' notice ' ;
const INFO = ' info ' ;
const DEBUG = ' debug ' ; Puede llamar a los métodos de registro de acuerdo con el log level
| configuración | opción | descripción |
|---|---|---|
log_level | 1/1/2/3/4 | Nivel de registro |
log_path | Dónde almacenar archivos de registro. |
0 No haga ningún registro 1 LOG SOLO Error 2 Error de registro 、 Advertencia 、 Observe 3 Error 、 Advertencia 、 Aviso 、 Información 4 Registro todo
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 callingUso
Suponga que un archivo se carga con este formulario HTML:
< form method =" POST " enctype =" multipart/form-data " >
< input type =" file " name =" foo " value ="" />
< input type =" submit " value =" Upload File " />
</ form >Cuando se envía el formulario HTML, el código PHP del lado del servidor puede validar y cargar el archivo como este:
<?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 ();
} Si desea que su URI sea más corto, la url rewrite lo ayudará a ocultar index.php en 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 ;
}Si su proyecto no es el directorio raíz
Por ejemplo, su proyecto se encuentra en /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 ;
} Si está deseando reescribir URL, asegúrese de haber habilitado rewrite module Apache. Ya hemos escrito el archivo .htaccess en el directorio de marco para usted.
Aquí está la configuración de 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>