이 라이브러리는 비즈니스 로직을 간단하고 강력한 정의로 저장하는 데 사용됩니다.
PHP의 미니 스크립트 언어. 세 가지 간단한 작업을 수행합니다.
예를 들어 :
when var1>5 and var2>20 then var3=20 // when and then
init var5=20 when var1>5 and var2>20 then var3=var5 // init, when and then
init var5=20 when var1>5 and var2>20 then var3=var5 else var3=var20 // init, when, then and else
when var1>$abc then var3=var5 // $abc is a PHP variable.
때때로 우리는 "일부 값이 동일하다면 다른 코드를 설정하거나 실행하는 것"의 기준으로 임의 코드를 실행해야합니다.
PHP에서는 다음 코드를 수행 할 수 있습니다.
if ( $ condition ) {
$ variable = 1 ;
}그러나이 코드는 런타임에 실행됩니다. 특정 시점 에서이 코드를 실행 해야하는 경우 어떻게해야합니까?.
다음 코드를 수행 할 수 있습니다.
$ script = ' if($condition) {
$variable=1;
} ' ;
// and later..
eval ( $ script );이 솔루션은 작동하며 명령을 평가하는 경우에만 실행됩니다). 그러나 그것은 장점이며 오류가 발생하기 쉬우 며 위험합니다.
우리의 도서관은 동일하지만 안전하고 깨끗합니다.
$ mini -> separate ( " when condition then variable=1 " );작곡가를 사용하여 설치 :
작곡가는 eftec/minilang이 필요합니다
새로운 프로젝트 만들기
use eftec minilang MiniLang ;
include " ../lib/MiniLang.php " ; // or the right path to MiniLang.php
$ mini = new MiniLang ();
$ mini -> separate ( " when field1=1 then field2=2 " ); // we set the logic of the language but we are not executed it yet.
$ mini -> separate ( " when field1=2 then field2=4 " ); // we set more logic.
$ result =[ ' field1 ' => 1 , ' field2 ' => 0 ]; // used for variables.
$ callback = new stdClass (); // used for callbacks if any
$ mini -> evalAllLogic ( $ callback , $ result );
var_dump ( $ result );Another example:
use eftec minilang MiniLang ;
include " ../lib/MiniLang.php " ;
$ result =[ ' var1 ' => ' hello ' ];
$ global1 = " hello " ;
$ mini = new MiniLang ( null , $ result );
$ mini -> throwError = false ; // if error then we store the errors in $mini->errorLog;
$ mini -> separate ( ' when var1="hello" then var2="world" ' ); // if var1 is equals "hello" then var2 is set "world"
$ mini -> separate ( ' when $global1="hello" then $global2="world" ' ); // we can also use php variables (global)
$ mini -> evalAllLogic ( false ); // false means it continues to evaluate more expressions if any
// (true means that it only evaluates the first expression where "when" is valid)
var_dump ( $ result ); // array(2) { ["var1"]=> string(5) "hello" ["var2"]=> string(5) "world" }
var_dump ( $ global2 ); // string(5) "world" __construct (& $ caller, & $ dict, array $ specialcom = [], $ areaname = [], $ serviceclass = null)
이전 정의를 재설정하지만 변수, 서비스 및 영역은 재설정됩니다.
발신자 객체를 설정하십시오. 발신자 객체는 스크립트 내부에서 호출 될 수있는 메소드가있는 서비스 클래스 일 수 있습니다.
시스템에서 사용하는 변수로 사전을 설정하십시오.
그것은 미닐랑에 표현을 보내고 그 부분에서 분해됩니다. 스크립트는 실행되지 않고 구문 분석됩니다.
논리를 평가합니다. true 또는 false를 반환합니다.
값 또는 값을 설정합니다. 사실이 어디에 있는지 여부는 고려하지 않습니다.
부울.
문자열 배열. $ trowerror가 False 인 경우 모든 오류가 여기에 저장됩니다.
예:
$ this -> throwError = false ;
$ mini -> separate ( " when FIELDDOESNOTEXIST=1 then field2=2 " );
var_dump ( $ this -> errorLog );코드의 구문은 네 부분으로 분리됩니다. 시작, 위치 (또는시기), 설정 (또는 그 후) 및 기타.
예:
$ mini -> separate ( " when field1=1 then field2=2 " );필드 1 = 1이면 필드 2를 2로 설정합니다.
변수는 varname 에 의해 정의됩니다
예 : 예제/examplevariable.php
$ mini = new MiniLang ();
$ mini -> separate ( " when field1>0 then field2=3 " ); // we prepare the language
$ variables =[ ' field1 ' => 1 ]; // we define regular variables
$ callback = new stdClass ();
$ mini -> evalAllLogic ( $ callback , $ variables ); // we set the variables and run the languageand run the language
var_dump ( $ variables ); // field1=1, field2=3변수는 PHP 객체를 호스팅 할 수 있으며 그 안에있는 필드를 호출하고 액세스 할 수 있습니다.
varname.field
코드 예제/examplevariable2.php의 예
class MyModel {
var $ id = 1 ;
var $ value = "" ;
public function __construct ( $ id = 0 , $ value = "" )
{
$ this -> id = $ id ;
$ this -> value = $ value ;
}
}
class ClassCaller {
public function Processcaller ( $ arg ) {
echo " Caller: setting the variable { $ arg -> id } <br> " ;
}
}
class ClassService {
public function ProcessService ( $ arg ) {
echo " Service: setting the variable { $ arg -> id } <br> " ;
}
}
$ mini = new MiniLang ([],[], new ClassService ());
$ mini -> separate ( " when field1.id>0 then
field2.value=3
and field3.processcaller
and processcaller(field3)
and processservice(field3) " ); // we prepare the language
$ variables =[ ' field1 ' => new MyModel ( 1 , " hi " )
, ' field2 ' => new MyModel ( 2 , '' )
, ' field3 ' => new MyModel ( 3 , '' )]; // we define regular variables
$ callback = new ClassCaller ();
$ mini -> evalAllLogic ( $ callback , $ variables , false ); // we set the variables and run the languageand run the language
var_dump ( $ variables );변수는 연관/색인 배열을 보유 할 수 있으며 그 안에있는 요소를 읽고 액세스 할 수 있습니다.
예:
$ mini = new MiniLang ( null ,
[
' vararray ' =>[ ' associindex ' => ' hi ' , 0 => ' a ' , 1 => ' b ' , 2 => ' c ' , 3 => ' d ' , 4 => ' last ' , ' a ' =>[ ' b ' =>[ ' c ' => ' nested ' ]]]
]
);vararray.associndex // vararray['associindex'] ('hi')
vararray. 4 // vararray[4] 'last'
vararray. 123 // it will throw an error (out of index)
vararray. param ( ' a.b.c ' )) // vararray['a']['b']['c'] ('nested')
param (vararray, ' a.b.c ' )) // vararray['a']['b']['c'] ('nested')
vararray._first // first element ('hi')
vararray._last // last element ('last')
vararray._count // returns the number of elements. (6)코드 예제의 예/examplevariable_arr.php
class ClassCaller {
public function Processcaller ( $ arg ) {
echo " Caller: setting the variable { $ arg [ ' id ' ]} <br> " ;
}
}
class ClassService {
public function ProcessService ( $ arg ) {
echo " Service: setting the variable { $ arg [ ' id ' ]} <br> " ;
}
}
$ mini = new MiniLang ([],[], new ClassService ());
$ mini -> separate ( " when field1.id>0 then
field2.value=3
and field3.processcaller
and processcaller(field3)
and processservice(field3) " );
$ variables =[ ' field1 ' =>[ ' id ' => 1 , ' value ' => 3 ]
, ' field2 ' =>[ ' id ' => 2 , ' value ' => '' ]
, ' field3 ' =>[ ' id ' => 3 , ' value ' => '' ]
];
$ callback = new ClassCaller ();
$ mini -> evalAllLogic ( $ callback , $ variables , false );
var_dump ( $ variables );글로벌 변수는 PHP ($ global)의 값을 취하므로 언어 내부에서 정의하거나 설정할 필요가 없습니다.
참고 : 보안 목적. PHP에 의해 "$ _namevar"로 정의 된 글로벌 변수는 읽거나 수정할 수 없습니다. 따라서 글로벌 변수를 보호하려면 밑줄로 접두사로 이름을 바꿀 수 있습니다.
예 : 변수 $ _server를 읽으려고하면 정의되지 않은 변수 $ 서버의 값을 반환합니다.
글로벌 변수는에 의해 정의됩니다
$globalname
$ globalname .associndex // $globalname['associindex']
$ globalname . 4 // $globalname[4]
$ globalname . param ( ' a.b.c ' ) // $globalname['a']['b']['c']
param ( $ globalname , ' a.b.c ' ) // $globalname['a']['b']['c']예:
$globalname=30
예제 코드 : 예제/exampleglobal.php
$ field1 = 1 ; // our global variable
$ mini = new MiniLang ();
$ mini -> separate ( ' when $field1>0 then $field1=3 ' ); // we prepare the language
$ variables =[]; // local variables
$ callback = new stdClass ();
$ mini -> evalAllLogic ( $ callback , $ variables ); // we set the variables and run the languageand run the language
var_dump ( $ field1 ); // returns 3 | 유형 | 예 |
|---|---|
| 숫자 | 20 |
| 끈 | "Hello World", 'Hello World' |
| Stringp | "내 이름은 {{var}}입니다." |
| 기능 | 명칭 (Arg, Arg) |
var = 20 및 var2 = "hello"및 var3 = "hello {{var}}"및 var4 = fn ()
| 예약 된 단어 | 설명 |
|---|---|
| null () | 널 값 |
| 거짓() | 거짓 가치 |
| 진실() | 진정한 가치 |
| 에() | 1 |
| param (var, 'l1.l2.l3') | 배열 (var)을 var [ 'l1'] [ 'l2'] [ 'l3']로 분리합니다. |
| 끄다() | 0 |
| undef () | -1 (정의되지 않은 경우) |
| 튀기다() | (특별 가치). <-> OFF의 값을 반전시킵니다 value = flip ()로 사용 |
| 지금() | 현재 타임 스탬프 (정수)를 반환합니다. |
| 시간제 노동자() | 현재 타임 스탬프 (정수)를 반환합니다. |
| 간격() | 마지막 변경과 지금 사이의 간격 (초)을 반환합니다. 콜백 클래스의 Field DatelastChange 또는 메소드 DatelastChange ()를 사용합니다. |
| FullInterval () | 프로세스 시작과 지금 사이의 간격 (초)을 반환합니다. 콜백 클래스의 필드 날짜 또는 메소드 DateInit ()를 사용합니다. |
| contain ()/str_contains () | 텍스트가 다른 텍스트에 포함되어 있으면 true를 반환합니다.면 : str_contains (field1, 'hi') |
| str_starts_with (), startwith () | 텍스트가 다른 텍스트로 시작하면 true를 반환합니다 |
| str_ends_with (), endwith () | 텍스트가 다른 텍스트로 끝나면 true를 반환합니다. |
예 : 예제/examplereserved.php
$ mini = new MiniLang ();
$ mini -> separate ( " when true=true then field1=timer() " ); // we prepare the language
$ variables =[ ' field1 ' => 1 ]; // we define regular variables
$ callback = new stdClass ();
$ mini -> evalAllLogic ( $ callback , $ variables ); // we set the variables and run the language
var_dump ( $ variables );예제 타이머 : 예제/examplerervedtimer.php
class ClassWithTimer {
var $ dateLastChange ;
public function dateInit () {
return time ();
}
public function __construct ()
{
$ this -> dateLastChange = time ();
}
}
$ mini = new MiniLang ();
$ mini -> separate ( " when true=true then field1=interval() and field2=fullinterval() " ); // we prepare the language
$ variables =[ ' field1 ' => 0 , ' field2 ' => 0 ]; // we define regular variables
$ callback = new ClassWithTimer ();
$ mini -> evalAllLogic ( $ callback , $ variables ); // we set the variables and run the language
var_dump ( $ variables );표현식 의이 부분은 값을 설정할 수 있습니다. 이 표현은 일반적으로 선택 사항이며 생략 할 수 있습니다.
SET과 비슷하지만 어디에서 유효한 지에 관계없이 어디에서든 실행됩니다.
Init Counter = 20 여기서 변수 1 = 20 변수+카운터를 설정합니다
$ mini -> separate ( " init tmp=50 when condition=1 then field1+10 " ); // set tmp to 50. If condition is 1 then it increases the field1 by 10. 표현식 의이 부분은 진술에 조건을 추가합니다.
우리는 또한 "언제"를 사용할 수 있습니다.
표현
또는
표현 시
"또는"또는 "또는"로 분리하여 동시에 조건 이상을 비교할 수 있습니다.
여기서 v1 = 10 및 v2 = 20 또는 v3 <50
여기서 변수 1 = 20 및 $ variable2 = variable3 또는 함수 (20) = 40
여기서 $ Field = 20 및 Field2 <> 40 또는 Field3 = 40 // SQL 구문
여기서 $ field == 20 && field2! = 40 || Field3 =+40 // PHP 구문
여기서 1 // 항상 사실입니다
표현식 의이 부분을 사용하면 변수의 값을 설정할 수 있습니다. ","또는 "및"로 분리하여 둘 이상의 변수를 동시에 설정할 수 있습니다.
우리는 또한 "set"또는 "then"표현을 사용할 수 있습니다.
표현을 설정하십시오
또는
그런 다음 표현
표현식 의이 부분은 유효한 경우에만 실행됩니다.
다음 표현식을 사용하여 변수를 설정할 수 있습니다.
이 라이브러리는 다음과 같은 복잡한 명령을 허용하지 않습니다
변수 1 = 20 및 $ variable2 = variable3 및 함수 (20) = 40을 설정하십시오
$ mini -> separate ( " when condition=1 then field1+10 " ); // if condition is 1 then it increases the field1 by 10. 표현식 의이 선택적 부분을 사용하면 변수의 값을 설정할 수 있습니다. ","또는 "및"로 분리하여 둘 이상의 변수를 동시에 설정할 수 있습니다.
이 코드는 "여기서"가 수동으로 호출되는 경우 "Where"가 False를 반환하는 경우에만 평가됩니다.
else variable1 = 20 및 $ variable2 = variable3 및 함수 (20) = 40
"루프"공간을 사용하여 루프를 만들 수 있습니다.
루프를 시작하려면 작성해야합니다
$ this -> separate ( ' loop variableloop=variable_with_values ' );
// where variable_with_values is must contains an array of values
// variableloop._key will contain the key of the loop
// variableloop._value will contain the value of the loop 그리고 루프를 끝내려면 사용해야합니다
$ this -> separate ( ' loop end ' );"세트"또는 "else"에서 연산자 "break"를 사용하여 루프를 피할 수 있습니다.
$ this -> separate ( ' when condition set break else break ' );참고 : 루프는 모든 논리를 평가할 때만 평가됩니다. evallogic () 및 evallogic2 ()와 작동하지 않습니다.
참고 : 루프에 조건을 추가 할 수는 없지만 빈 배열을 할당하는 루프를 건너 뛸 수 있습니다.
예:
$ this -> separate ( ' loop $row=variable ' );
$ this -> separate ( ' loop $row2=variable ' );
$ this -> separate ( ' where op=2 then cc=2 ' );
$ this -> separate ( ' where op=3 then break ' ); // ends of the first loop
$ this -> separate ( ' loop end ' );
$ this -> separate ( ' loop end ' )
$ obj -> evalAllLogic (); 언어로 만든 논리로 클래스를 만들 수 있습니다. 목표는 코드의 성능을 높이는 것입니다.
클래스를 생성하려면 먼저 별도 () 대신 Method 2 ()를 사용하여 논리를 작성해야합니다. 논리를 클래스 인스턴스 배열 안에 저장합니다. 코드를 직접 사용하거나 다음과 같이 클래스 내부를 저장할 수 있습니다.
// create an instance of MiniLang
$ mini = new MiniLang ( null );
// the logic goes here
$ mini -> separate2 ( ' when var1="hello" and comp.f=false() then var2="world" ' ); // if var1 is equals "hello" then var2 is set "world"
// and the generation of the class
$ r = $ mini -> generateClass ( ' ExampleBasicClass ' , ' nsexample ' , ' ExampleBasicClass.php ' );호출 된 새 파일을 저장합니까? exampleBasicClass.php (예제를 확인할 수 있습니까? 예제/genclass/1.exampleBasic.php)
수업이 생성되면 Minilang 대신이 새로운 클래스를 사용할 수 있습니다. 이 클래스는 이미 컴파일되었으므로 빠르게 타 오르고 있습니다. 그러나 논리를 변경 해야하는 경우 다시 컴파일해야합니다. (예제/genclass/2.exampleBasic.php 및? example/genclass/examplebasicclass.php)를 확인할 수 있습니다.
$ result =[ ' var1 ' => ' hello ' ];
$ obj = new ExampleBasicClass ( null , $ result );
$ obj -> evalAllLogic ( true );수업은 다음과 같습니다.
<?php
namespace ns example ;
use eftec minilang MiniLang ;
class ExampleBasicClass extends MiniLang {
public $ numCode = 2 ; // num of lines of code
public $ usingClass = true ; // if true then we are using a class (this class)
public function whereRun ( $ lineCode = 0 ) {
// ...
} // end function WhereRun
public function setRun ( $ lineCode = 0 ) {
// ...
} // end function SetRun
public function elseRun ( $ lineCode = 0 ) {
// ...
} // end function ElseRun
public function initRun ( $ lineCode = 0 ) {
// ...
} // end function InitRun
} // end class여기서 각 방법은 표현식의 일부를 평가합니다.
examples/examplebenchmark.php
우리는 일부 작업을 1000 번이라고 부릅니다.
PHP에서 새로운 스크립팅 언어를 중간 창조