Git Product home page Git Product logo

php-scalar-objects's Introduction

PHP Scalar Object Handlers

Wouldn't you prefer to write PHP like this?

$n = 12.5;
echo $n->floor()->toString()->length(); // 2

Or deal with strings, without remembering the parameter order?

$str = "Hello World";
echo $str->replace("World","PHP"); // Hello PHP

$str = "Hello World";
echo $str->length();  //  11

Or chain array operations, with a simpler syntax API?

$arr = ["k1"=>"val1","k2"=>"val2"];
print_r($arr->merge(["k3"=>"val3","k4"=>"val4"])->count()) // 4

$array = [1,2,3,4,5];
$array->each(function(&$value) {
  $value *= 2;
});  // [2,4,6,8,10]

PHP6 Gives us a chance to create a new API to streamline the language in a way that ensures all old code still runs in the same way. Here's how to see this in action right now!

An Experimental Proposal for PHP Scalar Objects

Based on the fantastic extension by nikic https://github.com/nikic/scalar_objects this project is designed to start the ball rolling on the future API for Scalar objects in PHP.

Discussions, arguments and pull requests are welcome. Once we get some consensus, we can send a pull request up to nikic and hopefully get some discussion going on the internals list. Let's make PHP6 Awesome.

Note, the handlers won't actually be implemented in PHP, but the handlers and methods can be built natively once the API is agreed. This is just a way to get contributions from the wider PHP community without the need to know the internals.

Getting started

The handlers are written in PHP so, you don't need to install the extension to contribute, however full instructions for getting started are on the extension readme file at: https://github.com/nikic/scalar_objects

Supported types

Object handlers are supported for string, integer, array, float, null and resource

The handlers are PSR-4 loaded under the namespace Spl\Scalars in the src directory.

Arrays

Syntax available is as follows.

chunk(chunk size)

$array = ["first", "second", "third", "fourth", "fifth"];
$array->chunk(2);   //  [["first","second"],["third","fourth"],["fifth"]]

column(column key)

$array = [["key1"=>"value","key2"=>"value2"],["key1"=>"value","key2"=>"value2"]];
$array->column("key2");   //  ["value2","value2"]

combine(Array)

$array = ["k1","k2","k3","k4"];
$array2 = ["val","val2","val3","val4"];
$array->combine($array2);  //  ["k1"=>"val","k2"=>"val2","k3"=>"val3","k4"=>"val4"]

count()

$array = ["k1"=>"val","k2"=>"val2"];
$array->count();  //  2

diff(Array)

$array  = ["k1"=>"val","k2"=>"val2"];
$array2 = ["k2"=>"val2","k3"=>"val3"];
$array->diff($array2);  // ["k1" => "val"]

hasKey(keyname)

$array = ["k1"=>"val","k2"=>"val2"];
$array->hasKey("k2");  //  true

keys()

$array = ["k1"=>"val","k2"=>"val2"];
$array->keys();  //  ["k1","k2"]

merge(Array)

$array = ["k1"=>"val","k2"=>"val2"];
$array2 = ["k2"=>"val2","k3"=>"val3"];
$array->merge($array2);  //  ["k1"=>"val","k2"=>"val2","k3"=>"val3"]

push(value)

$array = ["k1"=>"val","k2"=>"val2"];
$array->push("val3");  //  ["k1"=>"val","k2"=>"val2",0=>"val3"]

rand()

$array = ["k1"=>"val","k2"=>"val2","k3"=>"val3"];
$array->rand();  //  "val3"

reverse()

$array = ["k1"=>"val","k2"=>"val2","k3"=>"val3"];
$array->reverse();  //  ["k3"=>"va3","k2"=>"val2","k1"=>"val"]

reindex(null | function($row))

$arr = [
  ["id"=>5, "val"=>"first"],["id"=>6, "val"=>"second"],["id"=>7, "val"=>"third"]
];
$array->reindex();  //  [0=>["id"=>5, "val"=>"first"],1=>["id"=>6, "val"=>"second"],2=>["id"=>7, "val"=>"third"]]
$array->reindex(function($row){return $row["id"]});  //  [5=>["id"=>5, "val"=>"first"],6=>["id"=>6, "val"=>"second"],7=>["id"=>7, "val"=>"third"]]

toJSON()

$array = ["k1"=>"val","k2"=>"val2","k3"=>"val3"];
$array->toJSON();  //  {"k1":"val","k2":"val2","k3":"val3"}

Strings

Syntax available is as follows.

length()

$str = "Hello World";
$str->length();  //  11

slice()

$str = "Hello World";
$str->slice(0,4);  // Hell

contains()

$str = "Hello World";
$str->contains("Hell");  // true

startsWith()

$str = "Hello World";
$str->startsWith("Help");  // false

endsWith()

$str = "Hello World";
$str->endsWith("rld");   // true

split()

$str = "Hello World";
$str->split(" ");  // ["Hello", "World"]

repeat()

$str = "Hello World";
$str->repeat(3);   // "Hello WorldHello WorldHello World"

reverse()

$str = "Hello World";
$str->reverse();   //  "dlroW olleH";

lower()

$str = "Hello World";
$str->lower();   // "hello world"

upper()

$str = "Hello World";
$str->upper();   // "HELLO WORLD"

toArray()

$str = "Hello World";
$str->toArray();   // [0=>"Hello World"]

Floats / Integers

abs()

$n = -25;
$n->abs();  // 25

ceil()

$n = 12.5;
$n->ceil();  // 13

floor()

$n = 12.5;
$n->floor();  // 12

toInt()

$n = 12.5;
$n->toInt();  // 12

Integers

even()

$n = 10;
$n->even();  // true

odd()

$n = 10;
$n->odd();   // false

Nulls

Syntax available is as follows.

$a = null;
$a->toJSON();  // null

php-scalar-objects's People

Contributors

davidstanley01 avatar eborden avatar hikari-no-yume avatar mnapoli avatar rossriley avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-scalar-objects's Issues

Array method dumping ground

I'll come back and give these some more detail, just getting them off the top of my head before I forget.

Member methods

  • join
  • sum
  • any
  • all
  • max
  • min
  • intersect
  • reduce/fold
  • map
  • filter
  • intersperse
  • union
  • difference
  • intersect
  • slice
  • splice

Static methods

  • repeat/fill
  • map **
  • filter **
  • reduce/fold **

**repeat, but these methods can be very helpful with partial application and member methods don't provide this opportunity

Add to packagist

I am uncertain if this has been asked before, but would it be possible to register this package on Packagist so that I can install is easily?

Following PSR standards?

This is a suggestion: how about following PSR-1 and PSR-2 for code formatting? I see that you are already following PSR-4, that would help to contribute people taking this project seriously I believe.

String.replace()

Hey,

while I do like the two prototypes for String.replace() it's actually an issue to properly document these two methods. I think it would be better to split them into two methods.

  • String.replace($search, $replacement) and
  • String.replaceMap(array $replacementMap)

While I'm not sure about the replaceMap method name. Suggestions are welcome.

gossi

hello + multibyte encoding support

Hi,

I was introduced to your project via a discussion on reddit.

I am wondering if you are still working on this, since there hasn't been much activity lately. If so, is multibyte encoding something you will support for strings?

thanks,

Member method partial application

One of the nice elements of PHP's scalar functions being represented as functions instead of member methods is that they allow for partial application. This is less intuitive with member methods since the eventual callee needs to provide a context and possibly additional arguments.

Functional Example

//Right handed partial application
function right_partial = ($callable, ...$rightArgs) {
    return function (...$leftArgs) use ($callable, $rightArgs) {
        return call_user_func_array($callable, array_merge($leftArgs, $rightArgs));
    };
} 

$strings = ['asfd', 'sdfg', 'setw', 'uyts', 'ghjk'];

// Partial application
array_map(right_partial('str_pos', 's', 0), $strings); //[1, 0, 0, 3, false]

// Inline
array_map(function ($str) {
    return str_pos($str, 's', 0);
}, $strings); //[1, 0, 0, 3, false]

Object Example

For member methods a special arrow function needs to exist to support these declarative techniques:

//Left handed partial application
function arrow ($method, $leftArgs) {
    return function ($context, $rightArgs) use ($method, $leftArgs) {
        return call_user_func_array([$context, $method], array_merge($leftArgs, $rightArgs));
    }
}

// Partial application
$strings->map(arrow('indexOf', 's', 0)); //[1, 0, 0, 3, false]

// Inline 
$strings->map(function ($str) {
    return $str->indexOf('s', 0);
}); //[1, 0, 0, 3, false]

Sugar

It would be nice if this could be sugared and provided at the language level. Options:

$strings->map(_->indexOf('s', 0)); //[1, 0, 0, 3, false]
$strings->map($->indexOf('s', 0)); //[1, 0, 0, 3, false]

Immutability

Value objects should be immutable.

So each method should return a new object, different from $this, and should not modify the current instance.

This is particularly true for Array, for example:

public function sort() {
    sort($this);
    return $this;
}

Should be:

public function sort() {
    $array = clone $this;
    $result = sort($array);

    if ($result === false) {
        throw new Exception(...);
    }

    return $array;
}

hello :)

Hi,

I'm also working on a project to shape the future API of php6, which can be found at gossi/oophp. Also part of this are objects for primitives.

Yesterday I published the project on php.internals and your project got mentioned and I'm asked about joining forces. I like your work and copied some of your methods to my php\lang\String class.

Would you also mind, checking out my project and how we could work on probably both projects?

Thanks
gossi

Array.has/indexOf

Array.indexOf(elem);
a -> int | string | false

$a = ['a', 'b', 'c'];
$a->indexOf('a'); //0
$a->indexOf('c'); //2
$a->indexOf('d'); //false

$a = ['a' => 1, 'b' => 2, 'c' => 3];
$a->indexOf(2); //'b'

Array.has(elem);
a -> bool

$a = ['a', 'b', 'c'];
$a->indexOf('a'); //true
$a->indexOf('d'); //false

ArrayHandler and StringHandler interface

Arrays and Strings can share some common ground in implementation details. For in reality a string is just a list of characters. This means many Array methods would have common application on strings.

ArrayHandler and StringHandler should share a common interface of ArrayLikeInterface. I'll put together a pull request for illustration.

Float.toPrecision/toFixed

Float.toPrecision(int)
int -> string

$f = 5.123456;
$f.toPrecision(); //"5.123456"
$f.toPrecision(5); //"5.1235"
$f.toPrecision(2); //"5.1"
$f.toPrecision(1); //"5"

Float.toFixed(int)
int -> string

$f = 5.123456;
$f.toFixed(); //"5.123456"
$f.toFixed(1); //"5.1"
$f.toFixed(2); //"5.12"
$f.toFixed(3); //"5.123"
$f.toFixed(10); //"5.1234560000"

Class names (singular/plural)

Current class names:

  • Arrays
  • Float
  • Integer
  • Nulls
  • Number
  • String

This is inconsistent, some are singular, some plurals.

I suggest the following naming:

  • Array
  • Float
  • Integer
  • Null
  • Number
  • String

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.