php

package module
Version: v0.0.0-...-9d111e7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 1, 2018 License: MIT Imports: 8 Imported by: 0

README

PHP bindings for Go

API Documentation MIT License

This package implements support for executing PHP scripts, exporting Go variables for use in PHP contexts, attaching Go method receivers as PHP classes and returning PHP variables for use in Go contexts.

Both PHP 5.x and PHP 7.x series are supported.

Building

Building this package requires that you have PHP installed as a library. For most Linux systems, this can usually be found in the php-embed package, or variations thereof.

Once the PHP library is available, the bindings can be compiled with go build and are go get-able.

Note: Building against PHP 5.x requires that the php5 tag is provided, i.e.:

go get -tags php5 github.com/deuill/go-php

This is due to the fact that PHP 7.x is the default build target.

Status

Executing PHP script files as well as inline strings is supported and stable.

Binding Go values as PHP variables is allowed for most base types, and PHP values returned from eval'd strings can be converted and used in Go contexts as interface{} values.

It is possible to attach Go method receivers as PHP classes, with full support for calling expored methods, as well as getting and setting embedded fields (for struct-type method receivers).

Caveats

Be aware that, by default, PHP is not designed to be used in multithreaded environments (which severely restricts the use of these bindings with Goroutines) if not built with ZTS support. However, ZTS support has seen major refactoring between PHP 5 and PHP 7, and as such is currently unsupported by this package.

Currently, it is recommended to either sync use of seperate Contexts between Goroutines, or share a single Context among all running Goroutines.

Roadmap

Currently, the package lacks in several respects:

  • ZTS/multi-threading support. This basically means using Go-PHP in Goroutines is severely limited.
  • Documentation and examples, both package-level and external.
  • Performance. There's no reason to believe Go-PHP suffers from any serious performance issues in particular, but adding benchmarks, especially compared against vanilla PHP, might help.
  • Your feature request here?

These items will be tackled in order of significance (which may not be the order shown above).

Usage

Basic

Executing a script is simple:

package main

import (
    php "github.com/deuill/go-php"
    "os"
)

func main() {
    engine, _ := php.New()

    context, _ := engine.NewContext()
    context.Output = os.Stdout

    context.Exec("index.php")
    engine.Destroy()
}

The above will execute script file index.php located in the current folder and will write any output to the io.Writer assigned to Context.Output (in this case, the standard output).

Binding and returning variables

The following example demonstrates binding a Go variable to the running PHP context, and returning a PHP variable for use in Go:

package main

import (
    "fmt"
    php "github.com/deuill/go-php"
)

func main() {
    engine, _ := php.New()
    context, _ := engine.NewContext()

    var str string = "Hello"
    context.Bind("var", str)

    val, _ := context.Eval("return $var.' World';")
    fmt.Printf("%s", val.Interface())
    // Prints 'Hello World' back to the user.

    engine.Destroy()
}

A string value "Hello" is attached using Context.Bind under a name var (available in PHP as $var). A script is executed inline using Context.Eval, combinding the attached value with a PHP string and returning it to the user.

Finally, the value is returned as an interface{} using Value.Interface() (one could also use Value.String(), though the both are equivalent in this case).

License

All code in this repository is covered by the terms of the MIT License, the full text of which can be found in the LICENSE file.

Documentation

Overview

Package engine provides methods allowing for the initialization and teardown of PHP engine bindings, off which execution contexts can be launched.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Context

type Context struct {
	// Output and Log are unbuffered writers used for regular and debug output,
	// respectively. If left unset, any data written into either by the calling
	// context will be lost.
	Output io.Writer
	Log    io.Writer

	// Header represents the HTTP headers set by current PHP context.
	Header http.Header
	// contains filtered or unexported fields
}

Context represents an individual execution context.

func (*Context) Bind

func (c *Context) Bind(name string, val interface{}) error

Bind allows for binding Go values into the current execution context under a certain name. Bind returns an error if attempting to bind an invalid value (check the documentation for NewValue for what is considered to be a "valid" value).

func (*Context) Destroy

func (c *Context) Destroy()

Destroy tears down the current execution context along with any active value bindings for that context.

func (*Context) Eval

func (c *Context) Eval(script string) (*Value, error)

Eval executes the PHP expression contained in script, and returns a Value containing the PHP value returned by the expression, if any. Any output produced is written context's pre-defined io.Writer instance.

func (*Context) Exec

func (c *Context) Exec(filename string) error

Exec executes a PHP script pointed to by filename in the current execution context, and returns an error, if any. Output produced by the script is written to the context's pre-defined io.Writer instance.

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine represents the core PHP engine bindings.

func New

func New() (*Engine, error)

New initializes a PHP engine instance on which contexts can be executed. It corresponds to PHP's MINIT (module init) phase.

func (*Engine) Define

func (e *Engine) Define(name string, fn func(args []interface{}) interface{}) error

Define registers a PHP class for the name passed, using function fn as constructor for individual object instances as needed by the PHP context.

The class name registered is assumed to be unique for the active engine.

The constructor function accepts a slice of arguments, as passed by the PHP context, and should return a method receiver instance, or nil on error (in which case, an exception is thrown on the PHP object constructor).

func (*Engine) Destroy

func (e *Engine) Destroy()

Destroy shuts down and frees any resources related to the PHP engine bindings.

func (*Engine) NewContext

func (e *Engine) NewContext() (*Context, error)

NewContext creates a new execution context for the active engine and returns an error if the execution context failed to initialize at any point. This corresponds to PHP's RINIT (request init) phase.

type Receiver

type Receiver struct {
	// contains filtered or unexported fields
}

Receiver represents a method receiver.

func (*Receiver) Destroy

func (r *Receiver) Destroy()

Destroy removes references to the generated PHP class for this receiver and frees any memory used by object instances.

func (*Receiver) NewObject

func (r *Receiver) NewObject(args []interface{}) (*ReceiverObject, error)

NewObject instantiates a new method receiver object, using the Receiver's create function and passing in a slice of values as a parameter.

type ReceiverObject

type ReceiverObject struct {
	// contains filtered or unexported fields
}

ReceiverObject represents an object instance of a pre-defined method receiver.

func (*ReceiverObject) Call

func (o *ReceiverObject) Call(name string, args []interface{}) *Value

Call executes a method receiver's named internal method, passing a slice of values as arguments to the method. If the method fails to execute or returns no value, nil is returned, otherwise a Value instance is returned.

func (*ReceiverObject) Exists

func (o *ReceiverObject) Exists(name string) bool

Exists checks if named internal property exists and returns true, or false if property does not exist.

func (*ReceiverObject) Get

func (o *ReceiverObject) Get(name string) (*Value, error)

Get returns a named internal property of the receiver object instance, or an error if the property does not exist or is not addressable.

func (*ReceiverObject) Set

func (o *ReceiverObject) Set(name string, val interface{})

Set assigns value to named internal property. If the named property does not exist or cannot be set, the method does nothing.

type Value

type Value struct {
	// contains filtered or unexported fields
}

Value represents a PHP value.

func NewValue

func NewValue(val interface{}) (*Value, error)

NewValue creates a PHP value representation of a Go value val. Available bindings for Go to PHP types are:

int             -> integer
float64         -> double
bool            -> boolean
string          -> string
slice           -> indexed array
map[int|string] -> associative array
struct          -> object

It is only possible to bind maps with integer or string keys. Only exported struct fields are passed to the PHP context. Bindings for functions and method receivers to PHP functions and classes are only available in the engine scope, and must be predeclared before context execution.

func NewValueFromPtr

func NewValueFromPtr(val unsafe.Pointer) (*Value, error)

NewValueFromPtr creates a Value type from an existing PHP value pointer.

func (*Value) Bool

func (v *Value) Bool() bool

Bool returns the internal PHP value as a boolean, converting if necessary.

func (*Value) Destroy

func (v *Value) Destroy()

Destroy removes all active references to the internal PHP value and frees any resources used.

func (*Value) Float

func (v *Value) Float() float64

Float returns the internal PHP value as a floating point number, converting if necessary.

func (*Value) Int

func (v *Value) Int() int64

Int returns the internal PHP value as an integer, converting if necessary.

func (*Value) Interface

func (v *Value) Interface() interface{}

Interface returns the internal PHP value as it lies, with no conversion step.

func (*Value) Kind

func (v *Value) Kind() ValueKind

Kind returns the Value's concrete kind of type.

func (*Value) Map

func (v *Value) Map() map[string]interface{}

Map returns the internal PHP value as a map of interface types, indexed by string keys. Non-array values are implicitly converted to single-element maps with a key of '0'.

func (*Value) Ptr

func (v *Value) Ptr() unsafe.Pointer

Ptr returns a pointer to the internal PHP value, and is mostly used for passing to C functions.

func (*Value) Slice

func (v *Value) Slice() []interface{}

Slice returns the internal PHP value as a slice of interface types. Non-array values are implicitly converted to single-element slices.

func (*Value) String

func (v *Value) String() string

String returns the internal PHP value as a string, converting if necessary.

type ValueKind

type ValueKind int

ValueKind represents the specific kind of type represented in Value.

const (
	Null ValueKind = iota
	Long
	Double
	Bool
	String
	Array
	Map
	Object
)

PHP types representable in Go.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL