Esta biblioteca é usada para armazenar a lógica de negócios em uma definição simples e ainda poderosa.
Uma mini linguagem de script para PHP. Ele faz três tarefas simples.
Por exemplo :
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.
Às vezes, precisamos executar o código arbitrário na base de "Se algum valor for igual a, definimos ou executamos outro código".
No PHP, poderíamos fazer o próximo código.
if ( $ condition ) {
$ variable = 1 ;
}No entanto, esse código é executado em tempo de execução. E se precisarmos executar esse código em algum ponto específico?.
Poderíamos fazer o próximo código:
$ script = ' if($condition) {
$variable=1;
} ' ;
// and later..
eval ( $ script );Esta solução funciona (e executa apenas se chamarmos o comando avaliar). Mas é detalhado, propenso a erros, e é perigoso.
Nossa biblioteca faz o mesmo, mas segura e limpa.
$ mini -> separate ( " when condition then variable=1 " );Instalando -o usando o compositor:
O compositor requer eftec/minilang
Criando um novo projeto
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 );Outro exemplo:
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)
Redefina as definições anteriores, mas as variáveis, serviços e áreas.
Defina um objeto de chamadas. O objeto do chamador pode ser uma classe de serviço com método que eles poderiam ser chamados dentro do script.
Defina um dicionário com as variáveis usadas pelo sistema.
Ele envia uma expressão para o Minilang e é decomposto em suas partes. O script não é executado, mas analisado.
Ele avalia uma lógica. Retorna verdadeiro ou falso.
Ele define um valor ou valores. Não considera se onde é verdadeiro ou não.
Booleano.
Matriz de string. Se $ Throwerror for falso, todos os erros serão armazenados aqui.
Exemplo:
$ this -> throwError = false ;
$ mini -> separate ( " when FIELDDOESNOTEXIST=1 then field2=2 " );
var_dump ( $ this -> errorLog );A sintaxe do código é separada em quatro partes. Init, onde (ou quando), defina (ou então) e mais.
Exemplo:
$ mini -> separate ( " when field1=1 then field2=2 " );Diz se Field1 = 1 então definimos Field2 como 2.
Uma variável é definida por varname
Exemplo: Exemplos/ExempliVariable.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=3Uma variável pode hospedar um objeto PHP e é possível ligar e acessar os campos dentro dele.
varname.field
Exemplo de exemplos de código/ExempliVariable2.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 );Uma variável pode conter uma matriz associativa/índice e é possível ler e acessar os elementos dentro dela.
Exemplo:
$ 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)Exemplo de exemplos de código/ExempliVariable_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 );Uma variável global leva os valores do PHP ($ global), por isso não precisa ser definido ou definido dentro do idioma
Nota: para fins de segurança. As variáveis globais definidas pelo PHP como "$ _namevar" não podem ser lidas ou modificadas. Portanto, se você deseja proteger uma variável global, poderá renomeá -la com um sublinhado como prefixo.
Exemplo: se você tentar ler a variável $ _Server, ele retornará o valor do servidor $ variável que ela pode ou não definir ou não.
Uma variável global é definida por
$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']Exemplo:
$globalname=30
Exemplo Código: Exemplos/ExempliGlobal.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 | Tipo | Exemplo |
|---|---|
| Número | 20 |
| corda | "Hello World", 'Hello World' |
| Stringp | "Meu nome é {{var}}" |
| função | Namefunction (arg, arg) |
set var = 20 e var2 = "hello" e var3 = "hello {{var}}" e var4 = fn ()
| Palavra reservada | Explicação |
|---|---|
| nulo() | valor nulo |
| falso() | valor falso |
| verdadeiro() | valor verdadeiro |
| sobre() | 1 |
| param (var, 'l1.l2.l3') | Separa uma matriz (var) em var ['l1'] ['l2'] ['l3'] |
| desligado() | 0 |
| undef () | -1 (para indefinido) |
| virar() | (valor especial). Inverte um valor <-> off Usado como valor = flip () |
| agora() | Retorna o registro de data e hora atual (número inteiro) |
| Timer () | Retorna o registro de data e hora atual (número inteiro) |
| intervalo() | Retorna o intervalo (em segundos) entre a última mudança e agora. Ele usa o campo DateLastChange ou Method DateLastChange () da classe de retorno de chamada |
| FullInterval () | Retorna o intervalo (em segundos) entre o início do processo e agora. Ele usa o campo dateInit ou método dateInit () da classe de retorno de chamada |
| contém ()/str_contains () | Retorna true se o texto estiver contido em outro texto. Exemplo: str_contains (Field1, 'Hi') |
| str_starts_with (), startwith () | retorna true se o texto começar com outro texto |
| str_ends_with (), endwith () | Retorna true se o texto terminar com outro texto. |
Exemplo: Exemplos/ExampleReReserved.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 );Exemplo de temporizador: exemplos/ExampleRereadertimer.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 );Esta parte da expressão permite definir um valor. Essa expressão é geralmente opcional e pode ser omitida.
É semelhante ao definido, mas é executado antes de onde e não importa se é válido ou não.
init contador = 20 onde variável1 = 20 define variável+contador
$ 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. Esta parte da expressão adiciona uma condição à declaração.
Também podemos usar "quando".
onde expressão
ou
quando expressão
É possível comparar mais do que uma condição ao mesmo tempo, separando -se por "e" ou "ou".
onde v1 = 10 e v2 = 20 ou v3 <50
onde variável1 = 20 e $ variável2 = variável3 ou função (20) = 40
onde $ field = 20 e field2 <> 40 ou field3 = 40 // sintaxe sql
onde $ field == 20 && field2! = 40 || campo3 =+40 // sintaxe php
onde 1 // sempre é verdade
Esta parte da expressão permite definir o valor de uma variável. É possível definir mais de uma variável ao mesmo tempo se separando por "," ou "e".
Também podemos usar a expressão "conjunto" ou "então"
Definir expressão
ou
então expressão
Esta parte da expressão é executada apenas se for válida
Poderíamos definir uma variável usando as próximas expressões:
Esta biblioteca não permite instruções complexas, como
set variable1 = 20 e $ variable2 = variável3 e função (20) = 40
$ mini -> separate ( " when condition=1 then field1+10 " ); // if condition is 1 then it increases the field1 by 10. Essa parte opcional da expressão permite definir o valor de uma variável. É possível definir mais de uma variável ao mesmo tempo se separando por "," ou "e".
Este código é avaliado apenas se "onde" retornar FALSE OF IF ELS OULHO é chamado manualmente.
else variável1 = 20 e $ variável2 = variável3 e função (20) = 40
É possível criar um loop usando o espaço "Loop"
Para iniciar um loop, você deve escrever
$ 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 E para encerrar o loop, você deve usar
$ this -> separate ( ' loop end ' );Você pode escapar do loop usando o operador "Break" no "conjunto" ou "Else".
$ this -> separate ( ' when condition set break else break ' );Nota: Os loops são avaliados apenas quando você avalia toda a lógica. Não funciona com evallogic () e evallogic2 ()
Nota: Você não pode adicionar uma condição a um loop, mas pode pular um loop atribuindo uma matriz vazia
Exemplo:
$ 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 (); É possível criar uma classe com a lógica criada no idioma. O objetivo é aumentar o desempenho do código.
Para gerar a classe, primeiro precisamos escrever a lógica usando o método separado2 () em vez de separado () . Ele armazenará a lógica dentro de uma matriz da instância da classe. Você pode usar o código diretamente ou economizar dentro de uma aula da seguinte maneira:
// 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 ' );Ele salvará um novo arquivo chamado? ExemploBasicClass.php (você pode verificar o exemplo? Exemplo/genclass/1.examplebasic.php)
Com a classe gerada, você pode usar esta nova classe em vez de Minilang . Como essa classe já está compilada, está em chamas rapidamente. No entanto, se você precisar alterar a lógica, precisará compilá -la novamente. (você pode verificar o exemplo? Exemplo/genclass/2.examplebasic.php e? Exemplo/genclass/exemplobasicclass.php)
$ result =[ ' var1 ' => ' hello ' ];
$ obj = new ExampleBasicClass ( null , $ result );
$ obj -> evalAllLogic ( true );A aula será:
<?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 classOnde cada método avalia uma parte da expressão.
Exemplos/exemplobenchmark.php
Chamamos algumas operações 1000 vezes.
Criando médio uma nova linguagem de script no PHP