Using another class from a thread - php

My threaded script doesn't see another class from within a thread. Here is my code.
require_once __DIR__.'\vendor\autoload.php';
use Symfony\Component\DomCrawler\Crawler;
$threadCount = 5;
$list = range(0,100);
$list = array_chunk($list, $threadCount);
foreach ($list as $line) {
$workers = [];
foreach (range(0,count($line)-1) as $i) {
$threadName = "Thread #".$i.": ";
$workers[$i] = new WorkerThreads($threadName,$line[$i]);
$workers[$i]->start();
}
foreach (range(0,count($line)-1) as $i) {
$workers[$i]->join();
}
}
class WorkerThreads extends Thread {
private $threadName;
private $num;
public function __construct($threadName,$num) {
$this->threadName = $threadName;
$this->num = $num;
}
public function run() {
if ($this->threadName && $this->num) {
$result = doThis($this->num);
printf('%sResult for number %s' . "\n", $this->threadName, $this->num);
}
}
}
function doThis($num){
$response = '<html><body><p class="message">Hello World!</p></body></html>';
$crawler = new Crawler($response);
$data = $crawler->filter('p')->text();
return $data;
}
When I run it, I get the following error message
Fatal error: Class 'Symfony\Component\SomeComponent\SomeClass' not found
How would I make my thread see another class?

With the help of #Federkun answer, which he deleted, I found the following thread discussing the issue
Here is a working solution
$autoloader = require __DIR__.'\vendor\autoload.php';
use Symfony\Component\DomCrawler\Crawler;
$threadCount = 1;
$list = range(0,100);
$list = array_chunk($list, $threadCount);
foreach ($list as $line) {
$workers = [];
foreach (range(0,count($line)-1) as $i) {
$threadName = "Thread #".$i.": ";
$workers[$i] = new WorkerThreads($autoloader,$threadName,$line[$i]);
$workers[$i]->start();
}
foreach (range(0,count($line)-1) as $i) {
$workers[$i]->join();
}
}
class WorkerThreads extends Thread {
private $threadName;
private $num;
public function __construct(Composer\Autoload\ClassLoader $loader,$threadName,$num) {
$this->threadName = $threadName;
$this->num = $num;
$this->loader = $loader;
}
public function run() {
$this->loader->register();
if ($this->threadName && $this->num) {
$result = doThis($this->num);
printf('%sResult for number %s' . "\n", $this->threadName, $this->num);
}
}
}
function doThis($num){
$response = '<html><body><p class="message">Hello World!</p></body></html>';
$crawler = new Crawler($response);
$data = $crawler->filter('p')->text();
return $data;
}

Related

PHP catching excepion from another class in a loop

I'm total PHP newbie, learning while creating following app. I got stuck trying to catch exception which breaks the loop in class Basic. Exception comes from class ProductVariation. Function generateRandomItems should generate random items on base of class Product and product.json file and skip productVariation when color is null.
<?php
class Product implements Item
{
public $id;
public $name;
public $price;
public $quantity;
public function __construct($file)
{
if (!file_exists($file)) {
throw new Exception('ProductFileNotFound');
}
$data = file_get_contents($file);
$product = json_decode($data);
$id = $product->id;
$name = $product->name;
$price = $product->price;
$quantity = $product->quantity;
$this->id = $id;
$this->name = $name;
$this->price = $price;
$this->quantity = $quantity;
}
public function getAmount()
{
$this->amount = $this->price * $this->quantity;
return $this->amount;
}
public function __toString()
{
$output = '';
foreach ($this as $key => $val) {
$output .= $key . ': ' . $val . "<br>";
}
return $output;
}
public function getId()
{
return $this->id;
}
public function getNet($vat = 0.23)
{
return round($this->price / (1 + $vat), 2);
}
}
class ProductVariation extends Product
{
public $color;
public function __construct($file, $color)
{
parent::__construct($file);
$this->color = $color;
if (!is_string($color)) {
throw new Exception('UndefinedVariantColor');
}
return $this->color;
}
}
interface Item
{
public function getId();
public function getNet($vat);
}
class Products extends ArrayIterator
{
public function __construct($file, $color)
{
$this->product = new Product($file);
$this->productVariation = new ProductVariation($file, $color);
}
}
class Basic
{
public function generateRandomString($randomLength)
{
$characters = 'abcdefghijklmnopqrstuvwxyz';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $randomLength; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
public function generateRandomItems($length)
{
$colors = array(
"red", "green", "blue",
"white", "black", null,
);
$list = [];
for ($i = 2; $i < $length + 2; $i += 2) {
$color = $colors[array_rand($colors, 1)];
$products = new Products('product.json', $color);
$products->product->id = $i - 1;
$products->product->name = $this->generateRandomString(rand(3, 15));
$products->product->price = rand(99, 10000) / 100;
$products->product->quantity = rand(0, 99);
$products->productVariation->id = $i;
$products->productVariation->name = $this->generateRandomString(rand(3, 15));
$products->productVariation->price = rand(99, 10000) / 100;
$products->productVariation->quantity = rand(0, 99);
echo $products->product;
echo $products->productVariation;
array_push($list, $products->product, $products->productVariation);
}
$uid = uniqid();
$fp = fopen("products/" . $uid . '.json', 'w');
fwrite($fp, json_encode($list));
fclose($fp);
}
}
product.json file content is {"id":1,"name":"Produkt testowy","price":13.99,"quantity":19}
For one, the check should precede the assignment to check if it’s null (this is in your Basic class).
// put check first
if (!is_string($color)) {
throw new Exception('UndefinedVariantColor');
}
$this->color = $color;

How to pass data from child process to master process by php pcntl?

I start some pcntl process to calculate some data, and I want to wait all child process end ,and send all return data to master process.
How Can I do that?
my pnctl trait like that:
<?php namespace App\Console\Commands;
trait PcntlTrait
{
private $workers = 1;
public function worker($count)
{
$this->worker = $count;
}
public function pcntl_call($all, \Closure $callback)
{
$count = count($all);
$perNum = ceil($count / $this->workers);
for($i = 0; $i < $this->workers; $i++){
$pids[$i] = pcntl_fork();
switch ($pids[$i]) {
case -1:
echo "fork error : {$i} \r\n";
exit;
case 0:
$start = $i * $perNum;
return $callback(array_slice($all, $start, $perNum));
exit;
default:
break;
}
}
$ret = [];
foreach ($pids as $i => $pid) {
if($pid) {
pcntl_waitpid($pid, $info);
$ret = array_merge($ret, $info);
}
}
return $ret;
}
}
and my TestCase Like that:
<?php
use App\Console\Commands\PcntlTrait;
class PcntlImp
{
use PcntlTrait;
}
class TestPcntlTrait extends \TestCase
{
public function setup()
{
$this->createApplication();
}
public function testPcntlCall()
{
$arr = [1,2,3,4,5,6,7,8,9,10];
$imp = new \PcntlImp();
$imp->worker(1);
$data = $imp->pcntl_call($arr, function($info){
if (empty($info)){
return [];
}
$ret = [];
foreach ($info as $item) {
$ret[] = $item * $item;
}
return $ret;
});
$this->assertCount(10, $data);
}
}
But I can got the error:
array_merge(): Argument #2 is not an array
and I know the second arg of pcntl_wait function is status not return data. But I do not know how to do?

Amazon Scraper Script works on XAMPP Windows but not PHP5 Cli on Linux

I'm trying to scrape Amazon ASIN codes using the below code:
<?php
class Scraper {
const BASE_URL = "http://www.amazon.com";
private $categoryFile = "";
private $outputFile = "";
private $catArray;
private $currentPage = NULL;
private $asin = array();
private $categoriesMatched = 0;
private $categoryProducts = array();
private $pagesMatched = 0;
private $totalPagesMatched = 0;
private $productsMatched = 0;
public function __construct($categoryFile, $outputFile) {
$this->categoryFile = $categoryFile;
$this->outputFile = $outputFile;
}
public function run() {
$this->readCategories($this->categoryFile);
$this->setupASINArray($this->asin);
$x = 1;
foreach ($this->catArray as $cat) {
$this->categoryProducts["$x"] = 0;
if ($this->currentPage == NULL) {
$this->currentPage = $cat;
$this->scrapeASIN($this->currentPage, $x);
$this->pagesMatched++;
}
if ($this->getNextPageLink($this->currentPage)) {
do {
// next page found
$this->pagesMatched++;
$this->scrapeASIN($this->currentPage, $x);
} while ($this->getNextPageLink($this->currentPage));
}
echo "Category complete: $this->pagesMatched Pages" . "\n";
$this->totalPagesMatched += $this->pagesMatched;
$this->pagesMatched = 0;
$this->writeASIN($this->outputFile, $x);
$x++;
$this->currentPage = NULL;
$this->categoriesMatched++;
}
$this->returnStats();
}
private function readCategories($categoryFile) {
$catArray = file($categoryFile, FILE_IGNORE_NEW_LINES);
$this->catArray = $catArray;
}
private function setupASINArray($asinArray) {
$x = 0;
foreach ($this->catArray as $cat) {
$asinArray["$x"][0] = "$cat";
$x++;
}
$this->asin = $asinArray;
}
private function getNextPageLink($currentPage) {
$document = new DOMDocument();
$html = file_get_contents($currentPage);
#$document->loadHTML($html);
$xpath = new DOMXPath($document);
$element = $xpath->query("//a[#id='pagnNextLink']/#href");
if ($element->length != 0) {
$this->currentPage = self::BASE_URL . $element->item(0)->value;
return true;
} else {
return false;
}
}
private function scrapeASIN($currentPage, $catNo) {
$html = file_get_contents($currentPage);
$regex = '~(?:www\.)?ama?zo?n\.(?:com|ca|co\.uk|co\.jp|de|fr)/(?:exec/obidos/ASIN/|o/|gp/product/|(?:(?:[^"\'/]*)/)?dp/|)(B[A-Z0-9]{9})(?:(?:/|\?|\#)(?:[^"\'\s]*))?~isx';
preg_match_all($regex, $html, $asin);
foreach ($asin[1] as $match) {
$this->asin[$catNo-1][] = $match;
}
}
private function writeASIN($outputFile, $catNo) {
$fh = fopen($outputFile, "a+");
$this->fixDupes($catNo);
$this->productsMatched += (count($this->asin[$catNo-1]) - 1);
$this->categoryProducts["$catNo"] = (count($this->asin[$catNo-1]) - 1);
flock($fh, LOCK_EX);
$x = 0;
foreach ($this->asin[$catNo-1] as $asin) {
fwrite($fh, "$asin" . "\n");
$x++;
}
flock($fh, LOCK_UN);
fclose($fh);
$x -= 1;
echo "$x ASIN codes written to file" . "\n";
}
private function fixDupes($catNo) {
$this->asin[$catNo-1] = array_unique($this->asin[$catNo-1], SORT_STRING);
}
public function returnStats() {
echo "Categories matched: " . $this->categoriesMatched . "\n";
echo "Pages parsed: " . $this->totalPagesMatched . "\n";
echo "Products parsed: " . $this->productsMatched . "\n";
echo "Category breakdown:" . "\n";
$x = 1;
foreach ($this->categoryProducts as $catProds) {
echo "Category $x had $catProds products" . "\n";
$x++;
}
}
}
$scraper = new Scraper($argv[1], $argv[2]);
$scraper->run();
?>
But it works fine on XAMPP on Windows but not on Linux. Any ideas as to why this may be? Sometimes it scrapes 0 ASIN's to file, sometimes it only scrapes 1 page in a category of 400+ pages. But the output/functionality is totally fine in Windows/XAMPP.
Any thoughts would be greatly appreciated!
Cheers
- Bryce
So try to change this way, just to avoid the error messages:
private function readCategories($categoryFile) {
if (file_exists($categoryFile)) {
$catArray = file($categoryFile, FILE_IGNORE_NEW_LINES);
$this->catArray = $catArray;
} else {
echo "File ".$categoryFile.' not exists!';
$this->catArray = array();
}
}

Return files from specified directory where Filesize is less than 40kb

i want to select file form directory where filezise in less then 100kb. please check my code its not working
<?php
ob_start();
$dir = '/home/couponsc/public_html/testfile';
$ext = '.mp3';
$search = $_GET['s'];
$results = glob("$dir/*$search*$ext");
foreach($results as $item)
{
$sizes= filesize($item);
if($sizes < 100);
{
echo $item;
}
}
?>
if($sizes < 100);
You have a semi-colon after your if-clause -> empty statement.
foreach($results as $item) {
$sizes= filesize($item);
if($sizes < 40*1024) {
echo $item, "\n";
}
}
Or with a bit more spl/lambda fun + recursion:
<?php
$path = 'c:/temp';
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::LEAVES_ONLY
);
$it = new FooFilterIterator($it, function($e) { return $e->getSize(); }, function($e) { return $e < 40*1024; } );
foreach($it as $f) {
printf("% 6d %s\n", $f->getSize(), $f);
}
class FooFilterIterator extends FilterIterator {
protected $getter;
protected $filter;
public function __construct(Iterator $source, $getter, $filter) {
parent::__construct($source);
$this->getter = $getter;
$this->filter = $filter;
}
public function accept() {
$f = $this->filter;
$g = $this->getter;
return $f( $g($this->current()) );
}
}
there's also the GlobIterator.
The filesize() function returns bytes, and not kilobytes, thus your condition doesn't work.
the correct condition is:
if($sizes < 102400);

Implement linked list in php

How should I implement a linked list in PHP? Is there a implementation built in into PHP?
I need to do a lot of insert and delete operations, and at same time I need to preserve order.
I'd like to use only PHP without any special extensions.
There is SplDoublyLinkedList. Is this okay, too?
Here is a linked list implementation in PHP pulled from: http://www.codediesel.com/php/linked-list-in-php/ which can add, delete, reverse and empty a linkedlist in PHP.
<?php
class ListNode
{
public $data;
public $next;
function __construct($data)
{
$this->data = $data;
$this->next = NULL;
}
function readNode()
{
return $this->data;
}
}
class LinkList
{
private $firstNode;
private $lastNode;
private $count;
function __construct()
{
$this->firstNode = NULL;
$this->lastNode = NULL;
$this->count = 0;
}
//insertion at the start of linklist
public function insertFirst($data)
{
$link = new ListNode($data);
$link->next = $this->firstNode;
$this->firstNode = &$link;
/* If this is the first node inserted in the list
then set the lastNode pointer to it.
*/
if($this->lastNode == NULL)
$this->lastNode = &$link;
$this->count++;
}
//displaying all nodes of linklist
public function readList()
{
$listData = array();
$current = $this->firstNode;
while($current != NULL)
{
array_push($listData, $current->readNode());
$current = $current->next;
}
foreach($listData as $v){
echo $v." ";
}
}
//reversing all nodes of linklist
public function reverseList()
{
if($this->firstNode != NULL)
{
if($this->firstNode->next != NULL)
{
$current = $this->firstNode;
$new = NULL;
while ($current != NULL)
{
$temp = $current->next;
$current->next = $new;
$new = $current;
$current = $temp;
}
$this->firstNode = $new;
}
}
}
//deleting a node from linklist $key is the value you want to delete
public function deleteNode($key)
{
$current = $this->firstNode;
$previous = $this->firstNode;
while($current->data != $key)
{
if($current->next == NULL)
return NULL;
else
{
$previous = $current;
$current = $current->next;
}
}
if($current == $this->firstNode)
{
if($this->count == 1)
{
$this->lastNode = $this->firstNode;
}
$this->firstNode = $this->firstNode->next;
}
else
{
if($this->lastNode == $current)
{
$this->lastNode = $previous;
}
$previous->next = $current->next;
}
$this->count--;
}
//empty linklist
public function emptyList()
{
$this->firstNode == NULL;
}
//insertion at index
public function insert($NewItem,$key){
if($key == 0){
$this->insertFirst($NewItem);
}
else{
$link = new ListNode($NewItem);
$current = $this->firstNode;
$previous = $this->firstNode;
for($i=0;$i<$key;$i++)
{
$previous = $current;
$current = $current->next;
}
$previous->next = $link;
$link->next = $current;
$this->count++;
}
}
}
$obj = new LinkList();
$obj->insertFirst($value);
$obj->insert($value,$key); // at any index
$obj->deleteNode($value);
$obj->readList();
Here is the code in php which will implement Linked List, only with the reference of head node i.e first node and then you add at first, last and delete a key, and also maintain the code of the keys in list.
<?php
/**
* Class Node
*/
class Node
{
public $data;
public $next;
public function __construct($item)
{
$this->data = $item;
$this->next = null;
}
}
/**
* Class LinkList
*/
class LinkList
{
public $head = null;
private static $count = 0;
/**
* #return int
*/
public function GetCount()
{
return self::$count;
}
/**
* #param mixed $item
*/
public function InsertAtFist($item) {
if ($this->head == null) {
$this->head = new Node($item);
} else {
$temp = new Node($item);
$temp->next = $this->head;
$this->head = $temp;
}
self::$count++;
}
/**
* #param mixed $item
*/
public function InsertAtLast($item) {
if ($this->head == null) {
$this->head = new Node($item);
} else {
/** #var Node $current */
$current = $this->head;
while ($current->next != null)
{
$current = $current->next;
}
$current->next = new Node($item);
}
self::$count++;
}
/**
* Delete the node which value matched with provided key
* #param $key
*/
public function Delete($key)
{
/** #var Node $current */
$current = $previous = $this->head;
while($current->data != $key) {
$previous = $current;
$current = $current->next;
}
// For the first node
if ($current == $previous) {
$this->head = $current->next;
}
$previous->next = $current->next;
self::$count--;
}
/**
* Print the link list as string like 1->3-> ...
*/
public function PrintAsList()
{
$items = [];
/** #var Node $current */
$current = $this->head;
while($current != null) {
array_push($items, $current->data);
$current = $current->next;
}
$str = '';
foreach($items as $item)
{
$str .= $item . '->';
}
echo $str;
echo PHP_EOL;
}
}
$ll = new LinkList();
$ll->InsertAtLast('KP');
$ll->InsertAtLast(45);
$ll->InsertAtFist(11);
$ll->InsertAtLast('FE');
$ll->InsertAtFist('LE');
$ll->InsertAtFist(100);
$ll->InsertAtFist(199);
$ll->InsertAtLast(500);
$ll->PrintAsList();
echo 'Total elements ' . $ll->GetCount();
echo PHP_EOL;
$ll->Delete(45);
$ll->PrintAsList();
echo 'Total elements ' . $ll->GetCount();
echo PHP_EOL;
$ll->Delete(500);
$ll->PrintAsList();
echo 'Total elements ' . $ll->GetCount();
echo PHP_EOL;
$ll->Delete(100);
$ll->PrintAsList();
echo 'Total elements ' . $ll->GetCount();
echo PHP_EOL;
Code out put as:
$ php LinkList.php
199->100->LE->11->KP->45->FE->500->
Total elements 8
199->100->LE->11->KP->FE->500->
Total elements 7
199->100->LE->11->KP->FE->
Total elements 6
199->LE->11->KP->FE->
Total elements 5
Here is another Linked list implementation using an array of elements. The add function keeps the elements sorted.
<?php
class LinkedList{
private $_head = null;
private $_list = array();
public function addNode($val) {
// add the first element
if(empty($this->_list)) {
$this->_head = $val;
$this->_list[$val] = null;
return;
}
$curr = $this->_head;
while ($curr != null || $curr === 0) {
// end of the list
if($this->_list[$curr] == null) {
$this->_list[$curr] = $val;
$this->_list[$val] = null;
return;
}
if($this->_list[$curr] < $val) {
$curr = $this->_list[$curr];
continue;
}
$this->_list[$val] = $this->_list[$curr];
$this->_list[$curr] = $val;
return;
}
}
public function deleteNode($val) {
if(empty($this->_list)) {
return;
}
$curr = $this->_head;
if($curr == $val) {
$this->_head = $this->_list[$curr];
unset($this->_list[$curr]);
return;
}
while($curr != null || $curr === 0) {
// end of the list
if($this->_list[$curr] == null) {
return;
}
if($this->_list[$curr] == $val) {
$this->_list[$curr] = $this->_list[$val];
unset($this->_list[$val]);
return;
}
$curr = $this->_list[$curr];
}
}
function showList(){
$curr = $this->_head;
while ($curr != null || $curr === 0) {
echo "-" . $curr;
$curr = $this->_list[$curr];
}
}
}
$list = new LinkedList();
$list->addNode(0);
$list->addNode(3);
$list->addNode(7);
$list->addNode(5);
$list->addNode(2);
$list->addNode(4);
$list->addNode(10);
$list->showList();
echo PHP_EOL;
$list->deleteNode(3);
$list->showList();
echo PHP_EOL;
$list->deleteNode(0);
$list->showList();
echo PHP_EOL;
The output is:
-0-2-3-4-5-7-10
-0-2-4-5-7-10
-2-4-5-7-10
I was also trying to write a program to create a linked list in PHP. Here is what I have written and it worked for me. I hope it helps to answer the question.
Created a php file. Name: LinkedList.php
{code}
<?php
require_once (__DIR__ . "/LinkedListNodeClass.php");
$node_1 = new Node();
Node::createNode($node_1, 5);
echo "\n Node 1 is created.";
$head = &$node_1;
echo "\n Head is intialized with Node 1.";
$node_2 = new Node();
Node::createNode($node_2, 1);
echo "\n Node 2 is created.";
Node::insertNodeInLinkedList($head, $node_2);
$node_3 = new Node();
Node::createNode($node_3, 11);
echo "\n Node 3 is created.";
Node::insertNodeInLinkedList($head, $node_3);
$node_4 = new Node();
Node::createNode($node_4, 51);
echo "\n Node 4 is created.";
Node::insertNodeInLinkedList($head, $node_4);
$node_5 = new Node();
Node::createNode($node_5, 78);
echo "\n Node 5 is created.";
Node::insertNodeInLinkedList($head, $node_5);
$node_6 = new Node();
Node::createNode($node_6, 34);
echo "\n Node 6 is created.";
Node::insertNodeInLinkedList($head, $node_6);
$node_7 = new Node();
Node::createNode($node_7, 99);
echo "\n Node 7 is created.";
Node::insertNodeInHeadOfLinkedList($head, $node_7);
$node_8 = new Node();
Node::createNode($node_8, 67);
echo "\n Node 8 is created.";
Node::insertNodeInHeadOfLinkedList($head, $node_8);
$node_9 = new Node();
Node::createNode($node_9, 101);
echo "\n Node 9 is created.";
Node::insertNodeAfterAPositionInLinkedList($head, 5, $node_9);
$node_10 = new Node();
Node::createNode($node_10, 25);
echo "\n Node 10 is created.";
Node::insertNodeAfterAPositionInLinkedList($head, 2, $node_10);
echo "\n Displaying the linked list: \n";
Node::displayLinkedList($head);
?>
{code}
This file is calling a class to create, insert and display nodes in linked list. Name: LinkedListNodeClass.php
{code}
<?php
class Node {
private $data;
private $next;
public function __construct() {
//does nothing...
}
//Creates a node
public function createNode($obj, $value) {
$obj->data = $value;
$obj->next = NULL;
}
//Inserts a created node in the end of a linked list
public function insertNodeInLinkedList($head, &$newNode) {
$node = $head;
while($node->next != NULL){
$node = $node->next;
}
$node->next = $newNode;
}
//Inserts a created node in the start of a linked list
public function insertNodeInHeadOfLinkedList(&$head, &$newNode) {
$top = $head;
$newNode->next = $top;
$head = $newNode;
}
//Inserts a created node after a position of a linked list
public function insertNodeAfterAPositionInLinkedList($head, $position, &$newNode) {
$node = $head;
$counter = 1;
while ($counter < $position){
$node = $node->next;
$counter++;
}
$newNode->next = $node->next;
$node->next = $newNode;
}
//Displays the Linked List
public function displayLinkedList($head) {
$node = $head;
print($node->data); echo "\t";
while($node->next != NULL){
$node = $node->next;
print($node->data); echo "\t";
}
}
}
?>
{code}
If don't think most people understand what linked lists are. The basic idea is you want to keep data organised is such a way that you can access the previous and next node using the current node. The other features like add, delete, insert, head etc are sugar, though necessary. I think the SPL package does cover a lot. Problem is I need a PHP 5.2.9 class. Guess I've to implement it myself.
Just to clarify, implementing linked list in PHP using PHP arrays probably is not a good idea, because PHP array is hash-table under the hood (not simple low-level arrays). Simultaneously, you don't get advantages of pointers.
Instead, you can implement data structures like linked list for PHP using extensions, that means you are implementing a data structure in C to PHP.
Spl data structures are an example, another example is php-ds extension, specially in case of linked lists, you can use this: https://www.php.net/manual/en/class.ds-sequence.php
Sequence ADT is the unification of List ADT and Vector ADT, so you can use Sequence ADT implemented data structures as lists.
Hope this could help someone choose wisely.
// Here's a basic implementation of SplDoublyLinkedList using PHP.
$splDoubleLinkedList = new SplDoublyLinkedList();
$splDoubleLinkedList->push('a');
$splDoubleLinkedList->push('3');
$splDoubleLinkedList->push('v');
$splDoubleLinkedList->push('1');
$splDoubleLinkedList->push('p');
// $splDoubleLinkedList->unshift('10');
// $splDoubleLinkedList->pop();
$splDoubleLinkedList->add(3, 3.0);
// First of all, we need to rewind list.
$splDoubleLinkedList->rewind();
// Use while, check if the list has valid node.
while($splDoubleLinkedList->valid()){
// Print current node's value.
echo $splDoubleLinkedList->current()."\n";
// Turn the cursor to next node.
$splDoubleLinkedList->next();
}

Categories