Download the PHP package pixelfederation/z-engine without Composer

On this page you can find all versions of the php package pixelfederation/z-engine. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package z-engine

!!! IMPORTANT !!! - THIS IS JUST A FORK OF THE UNMAINTAINED ORIGINAL PACKAGE FOR SPECIAL CASE USAGE WITH THE SWOOLE BUNDLE. NOTHING ELSE IS SUPPORTED !!!

Z-Engine library

Build Status GitHub release Minimum PHP Version License

Have you ever dreamed about mocking a final class or redefining final method? Or maybe have an ability to work with existing classes in runtime? Z-Engine is a PHP7.4 library that provides an API to PHP. Forget about all existing limitations and use this library to transform your existing code in runtime by declaring new methods, adding new interfaces to the classes and even installing your own system hooks, like opcode compilation, object initalization and much more.

:warning: DO NOT USE IT IN PRODUCTION UNTIL 1.0.0!

How it works?

As you know, PHP version 7.4 contains a new feature, called FFI. It allows the loading of shared libraries (.dll or .so), calling of C functions and accessing of C data structures in pure PHP, without having to have deep knowledge of the Zend extension API, and without having to learn a third "intermediate" language.

Z-Engine uses FFI to access internal structures of... PHP itself. This idea was so crazy to try, but it works! Z-Engine loads definition of native PHP structures, like zend_class_entry, zval, etc and manipulates them in runtime. Of course, it is dangerous, since FFI allows to work with structures on a very low level. Thus, you should expect segmentation faults, memory leaks and other bad things.

Pre-requisites and initialization

As this library depends on FFI, it requires PHP>=7.4 and FFI extension to be enabled. It should work in CLI mode without any troubles, whereas for web mode preload mode should be activated. Also, current version is limited to x64 non-thread-safe versions of PHP.

To install this library, simply add it via composer:

To activate a preload mode, please add Core::preload() call into your script, specified by opcache.preload. This call will be done during the server preload and will be used by library to bypass unnecessary C headers processing during each request.

Next step is to init library itself with short call to the Core::init():

Now you can test it with following example:

To have an idea, what you can do with this library, please see library tests as an example.

ReflectionClass

Library provides and extension for classic reflection API to manipulate internal structure of class via ReflectionClass:

Beside that, all methods that return ReflectionMethod or ReflectionClass were decorated to return an extended object with low-level access to native structures.

ReflectionMethod

ReflectionMethods contains methods to work with a definition of existing method:

ObjectStore API

Every object in PHP has it's own unique identifier, which can be received via spl_object_id($object). Sometimes we are looking for the way to get an object by it's identifier. Unfortunately, PHP doesn't provide such an API, whereas internally there is an instance of zend_objects_store structure which is stored in the global executor_globals variable (aka EG).

This library provides an ObjectStore API via Core::$executor->objectStore which implements an ArrayAccess and Countable interface. This means that you can get any existing object by accessing this store with object handle:

Object Extensions API

With the help of z-engine library it is possible to overload standard operators for your classes without diving deep into the PHP engine implementation. For example, let's say you want to define native matrix operators and use it:

There are two ways of activating custom handlers. First way is to implement several system interfaces like ObjectCastInterface, ObjectCompareValuesInterface, ObjectCreateInterface and ObjectDoOperationInterface. After that you should create an instance of ReflectionClass provided by this package and call installExtensionHandlers method to install extensions:

if you don't have an access to the code (eg. vendor), then you can still have an ability to define custom handlers. You need to define callbacks as closures explicitly and assign them via set***Handler() methods in the ReflectionClass.

Library provides following interfaces:

First one is ObjectCastInterface which provides a hook for handling casting a class instance to scalars. Typical examples are following: 1) explicit $value = (int) $objectInstance or implicit: $value = 10 + $objectInstance; in the case when do_operation handler is not installed. Please note, that this handler doesn't handle casting to array type as it is implemented in a different way.

To get the type of casting, you should check $hook->getCastType() method which will return the integer value of type. Possible values are declared as public constants in the ReflectionValue class. For example ReflectionValue::IS_LONG.

Next ObjectCompareValuesInterface interface is used to control the comparison logic. For example, you can compare two objects or even compare object with scalar values: if ($object > 10 || $object < $anotherObject)

Handler should check arguments which can be received by calling $hook->getFirst() and $hook->getSecond() methods (one of them should return an instance of your class) and return integer result -1..1. Where 1 is greater, -1 is less and 0 is equal.

The interface ObjectDoOperationInterface is the most powerful one because it gives you control over math operators applied to your object (such as ADD, SUB, MUL, DIV, POW, etc).

This handler receives an opcode (see OpCode::* constants) via $hook->getOpcode() and two arguments (one of them is an instance of class) via $hook->getFirst() and $hook->getSecond() and returns a value for that operation. In this handler you can return a new instance of your object to have a chain of immutable instances of objects.

Important reminder: you MUST install the create_object handler first in order to install hooks in runtime. Also you can not install the create_object handler for the object if it is internal one.

There is one extra method called setInterfaceGetsImplementedHandler which is useful for installing special handler for interfaces. The interface_gets_implemented callback uses the same memory slot as create_object handler for object, and will be called each time when any class will implement this interface. This gives interesting options for automatic class extensions registration, for example, if a class implements the ObjectCreateInterface then automatically call ReflectionClass->installExtensionHandlers() for it in callback.

Abstract Syntax Tree API

As you know, PHP7 uses an abstract syntax tree for working with abstract model of source code to simplify future development of language syntax. Unfortunately, this information is not provided back to the userland level. There are several PHP extensions like nikic/php-ast and sgolemon/astkit that provide low-level bindings to the underlying AST structures. Z-Engine provides access to the AST via Compiler::parseString(string $source, string $fileName = '') method. This method will return a top-level node of tree that implements NodeInterface. PHP has four types of AST nodes, they are: declaration node (classes, methods, etc), list node (can contain any number of children nodes), simple node (contains up to 4 children nodes, depending of type) and special value node class that can store any value in it (typically string or numeric).

Here are an example of parsing simple PHP code:

Output will be like that:

Node provides simple API to mutate children nodes via call to the Node->replaceChild(int $index, ?Node $node). You can create your own nodes in runtime or use a result from Compiler::parseString(string $source, string $fileName = '') as replacement for your code.

Modifying the Abstract Syntax Tree

When PHP 7 compiles PHP code it converts it into an abstract syntax tree (AST) before finally generating Opcodes that are persisted in Opcache. The zend_ast_process hook is called for every compiled script and allows you to modify the AST after it is parsed and created.

To install the zend_ast_process hook, make a static call to the Core::setASTProcessHandler(Closure $callback) method that accepts a callback which will be called during AST processing and will receive a AstProcessHook $hook as an argument. You can access top-level node item via $hook->getAST(): NodeInterface method.

You can see that result of evaluation is changed from "Yes" to "No" because we have adjusted given AST in our callback. But be aware, that this is one of the most complicated hooks to use, because it requires perfect understanding of the AST possibilities. Creating an invalid AST here can cause weird behavior or crashes.

Creating PHP extensions in runtime

The most interesting part of Z-Engine library is creating your own PHP extensions in PHP language itself. You do not have to spend a lot of time learning the C language; instead, you can use the ready-made API to create your own extension module from PHP itself!

Of course, not everything is possible to implement as an extension in PHP, for example, changing the parser syntax or changing the logic of opcache - for this you will have to delve into the code of the engine itself.

Let's make an example a module with global variables, an analog of apcu, so that these variables are not cleared after the request is completed. It is believed that PHP has the concept of share nothing and therefore can’t survive the boundary of the request, since at the time of completion of the request PHP will automatically free all allocated memory for objects. However, PHP itself can work with global variables, and they are stored inside loaded modules by the pointer zend_module_entry.globals_ptr.

Therefore, if we can register the module in PHP and allocate global memory for it, PHP will not clear it, and our module will be able to survive the boundary of the request.

Technically, every module is represented by following structure:

You can see that we can define several callbacks and there are several fields with meta-information about zts, debug, API version, etc that are used by PHP to check if this module can be loaded for current environment.

From PHP side, you should extend your module class from the AbstractModule class that contains general logic of module registration and startup and implement all required method from the ModuleInterface.

Let's have a look at our simple module:

Our SimpleCountersModule declares that it will use array of 10 unsigned ints. It also provides some information about required environment (debug/zts/API version). Important option is to mark our module persistent by returning true from targetPersistent() method. And now we are ready to register it and use it:

Note, that on subsequent requests module will be registered, this is why you should not call register twice. What is really cool is that any changes in module globals are true globals! They will be preserved between requests. Try to update each item to see that values in our array are increasing between requests:

Of course, module can declare any complex structure for globals and use it as required. If module requires some initialization, then you can implement the ControlModuleGlobalsInterface in your module and this callback will be called during module startup procedure. This may be useful for registration of additional hooks, class extensions, etc or for global variable initialization (filling it with predefined values, restoring state from DB/filesystem/etc)

Code of Conduct

This project adheres to the Contributor Covenant code of conduct. By participating, you are expected to uphold this code. Please report any unacceptable behavior.

License

This library is licensed under the MIT license.

Creating and maintaining this library is endless hard work for me. That's why there is one simple requirement for you: please give something back to the world. Whether that's code or financial support for this project is entirely up to you.


All versions of z-engine with dependencies

PHP Build Version
Package Version
Requires php Version 8.2.*
ext-ffi Version *
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package pixelfederation/z-engine contains the following files

Loading the files please wait ....