Page Text: A site about JavaScript development
Menu and widgets
How to add PHP method chaining or create a fluent interface?
Sometimes, we want to add PHP method chaining or create a fluent interface.
In this article, we’ll look at how to add PHP method chaining or create a fluent interface.
How to add PHP method chaining or create a fluent interface?
To add PHP method chaining or create a fluent interface, we return $this in our object.
For instance, we write
str = ""; } function addA() { $this->str .= "a"; return $this; } function addB() { $this->str .= "b"; return $this; } function getStr() { return $this->str; } } $a = new FakeString(); echo $a->addA()->addB()->getStr();
to create the FakeString class.
In it, we have the addA and addB return $this, which is the class instance, after concatenating a string to $this->str.
As a result, we can chain addA and addB like
$a->addA()->addB()->getStr()
since addA returns the class instance, which we use to call addB.
Conclusion
To add PHP method chaining or create a fluent interface, we return $this in our object.
Posted on
Sometimes, we want to create transactions with PHP and MySQL.
In this article, we’ll look at how to create transactions with PHP and MySQL.
How to create transactions with PHP and MySQL?
To create transactions with PHP and MySQL, we can use the beingTransaction and commit methods.
For instance, we write
try { $db->beginTransaction(); $db->query('first query'); $db->query('second query'); $db->query('third query'); $db->commit(); } catch (\Throwable $e) { $db->rollback(); throw $e; }
to call beginTransaction on the $db PDO connection object.
Then we call query to make the queries.
And then we call commit to commit the transaction if all the queries succeed.
We add a catch block to catch any errors raised by the queries.
And if there’re any errors, we call rollback to roll back the transaction.
Conclusion
To create transactions with PHP and MySQL, we can use the beingTransaction and commit methods.
Posted on
Sometimes, we want to handle multiple file uploads in PHP.
In this article, we’ll look at how to handle multiple file uploads in PHP.
How to handle multiple file uploads in PHP?
To handle multiple file uploads in PHP, we can loop through the $_FILES array to get all the uploaded files.
For instance, if we have a file input
Then we write
$total = count($_FILES['upload']['name']); for($i=0 ; $i < $total ; $i++) { $tmpFilePath = $_FILES['upload']['tmp_name'][$i]; if ($tmpFilePath != ""){ $newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i]; if(move_uploaded_file($tmpFilePath, $newFilePath)) { // ... } } }
to create a for loop that loops through $_FILES['upload']['name'].
We get the templ file path with $_FILES['upload']['tmp_name'][$i].
And the we get the file path to save the file to with
$newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i];
And then we call move_uploaded_file to move the file from $tmpFilePath to $newFilePath.
Conclusion
To handle multiple file uploads in PHP, we can loop through the $_FILES array to get all the uploaded files.
Posted on
Sometimes, we want to use braces with dynamic variable names in PHP.
In this article, we’ll look at how to use braces with dynamic variable names in PHP.
How to use braces with dynamic variable names in PHP?
To use braces with dynamic variable names in PHP, we wrap our variable name expression with braces.
For instance, we write
to create variables with "file" . $i inside the braces.
$i will be replaced with the actual value to form the variable name.
Conclusion
To use braces with dynamic variable names in PHP, we wrap our variable name expression with braces.
Posted on
Sometimes, we want to use multi-threading in PHP applications.
In this article, we’ll look at how to use multi-threading in PHP applications.
How to use multi-threading in PHP applications?
To use multi-threading in PHP applications, we can create a Thread subclass.
For instance, we write
class AsyncOperation extends Thread { public function __construct($arg) { $this->arg = $arg; } public function run() { if ($this->arg) { $sleep = mt_rand(1, 10); printf('%s: %s -start -sleeps %d' . "\n", date("g:i:sa"), $this->arg, $sleep); sleep($sleep); printf('%s: %s -finish' . "\n", date("g:i:sa"), $this->arg); } } } $stack = array(); foreach ( range("A", "D") as $i ) { $stack[] = new AsyncOperation($i); } foreach ( $stack as $t ) { $t->start(); }
to create the AsyncOperation class which is a subclass of the Thread class.
In the class, we add the run method that runs some code.
Then we create the $stack array and populate it with AsyncOperation objects.
And then we use a foreach loop to start the threads with start.
Conclusion
To use multi-threading in PHP applications, we can create a Thread subclass.
Posted on
Sometimes, we want to generate a random string with PHP.
In this article, we’ll look at how to generate a random string with PHP.
How to generate a random string with PHP?
To generate a random string with PHP, we can cxreate own function.
For instance, we write
function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; }
to define the generateRandomString that calls rand to get a random number between 0 and $charactersLength - 1 and use the returned value to get a random character from $characters.
We do that in the for loop to create a string with length $length by concatenating the random character to $randomString.
And then we return the string.
Conclusion
To generate a random string with PHP, we can cxreate own function.
Posted on
How to pass an array to a query using a WHERE clause with PHP?
Sometimes, we want to pass an array to a query using a WHERE clause with PHP.
In this article, we’ll look at how to pass an array to a query using a WHERE clause with PHP.
How to pass an array to a query using a WHERE clause with PHP?
To pass an array to a query using a WHERE clause with PHP, we create a string with the values in between the parentheses and interpolate them into the SQL string.
For instance, we write
$in = join(',', array_fill(0, count($ids), '?')); $select = <<prepare($select); $statement->bind_param(str_repeat('i', count($ids)), ...$ids); $statement->execute(); $result = $statement->get_result();
to create an array with the values with array_fill(0, count($ids), '?').
Then we join them with ', ' and assign the combined string to $in.
Then we add the placeholders into the $seelct string.
Then we call bind_params with 'i' repeated for the number of times equal to the count of $ids and the values in $ids.
Then we call execute to run the statement and call get_result to get the returned results.
Conclusion
To pass an array to a query using a WHERE clause with PHP, we create a string with the values in between the parentheses and interpolate them into the SQL string.
Posted on