The essential news about content management systems and mobile technology. Powered by Perfect Publisher and XT Search for Algolia.
The News Site publishes posts to the following channels: Facebook, Instagram, Twitter, Telegram, Web Push, Tumblr, and Blogger.
Looking at Laravel’s HTTP Tests documentation carefully, you’ll
notice some useful helpers built into the TestResponse
class to debug HTTP responses. This class recently had some
internal updates to these methods in the way of the Laravel 11's Dumpable Trait, and I thought it would be
a good time to revisit these useful helpers:
$response = $this->get('/');
$response->dump();
$response->dumpHeaders();
$response->dumpSession();
These methods have a dd()
counterpart too, which
will “die and dump” response values:
$response->dd();
$response->ddHeaders();
$response->ddSession();
These methods are helpful shortcuts to just doing this yourself in a test:
dump($response->headers->all());
// or
dd($response->headers->all());
However, where these methods shine is when you modify an
existing test that chains various assertions on the
TestResponse
instance:
$this->postJson(route('post.store', $post))
->assertSessionHasNoErrors()
->assertCreated()
->assertJson(['created' => true]);
Let’s say that assertSessionHasNoErrors()
fails,
and I want to debug. I’ve noticed when I come across a chain that
doesn’t assign the response, that I assign the response to a local
variable like so:
$response = $this->postJson(route('post.store', $post));
dd($response);
$response
->assertSessionHasNoErrors()
->assertCreated()
->assertJson(['created' => true]);
I will not argue whether you should chain assertions and never assign a local variable—that is more of a style preference—but you’ll come across situations where no local variable is assigned. Using these debug methods, we can quickly debug right before a test failure:
$this->postJson(route('post.store', $post))
+ ->dumpSession()
->assertSessionHasNoErrors()
->assertCreated()
->assertJson(['created' => true]);
These debug helpers are handy when you want to debug the
response somewhere between various assertions without grabbing the
TestResponse
instance in a local variable.
These features (and more) are covered in the Laravel
documentation for HTTP
Tests along with other useful TestResponse
features that make asserting JSON a breeze.
The post Debug Methods Built Into Laravel’s TestResponse appeared first on Laravel News.
Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.
Read more https://laravel-news.com/debugging-laravel-test-response
Read more https://build.prestashop-project.org/news/2024/do-you-speak-prestashop/
PHP 8.3 is the latest version of PHP. It has exciting new features and major improvements in performance. By upgrading to 8.3, you can achieve a significant increase in speed. In this article, we dive into how PHP 8.3 can be a game changer. It can speed up your application's performance.
PHP 8.3 introduces optimizations that enhance the runtime efficiency of your applications. This performance boost is more than a small upgrade. It's a significant improvement in the PHP engine. This leads to faster execution and uses fewer resources.
Several key improvements achieve this boost.
The Just-In-Time (JIT) compiler has been further optimized for better efficiency. The execution of scripts is faster and consumes less CPU time. This is especially beneficial for resource-intensive tasks.
PHP has refined how it handles opcodes (the instructions in the PHP bytecode). Version 8.3 uses more efficient ways to interpret and execute these opcodes. This reduces the execution time of scripts.
PHP 8.3 enhances the garbage collection mechanism, which is responsible for freeing memory occupied by unused objects. This results in more efficient memory usage and can significantly improve performance for memory-intensive applications.
Other improvements include optimizations for handling arrays and an enhanced type system. Preloading upgrades let server admins load and compile PHP code into memory right when the server starts. This reduces the overhead of compiling scripts on each request. It leads to faster response times.
These upgrades mean your existing PHP code will run faster and use fewer resources on PHP 8.3. All this without making any changes to your code!
PHP 8.3 also improves syntax, methods, and type safety. These new features indirectly upgrade performance. They reduce production errors and increase developer efficiency. This allows you to ship updates faster and address performance issues more effectively.
Some key improvements include
__clone
method. This allows for deep-cloning of
these properties. But the original property remains immutable.getBytesFromString()
method.
This method generates random strings from a given set of
characters. Additionally, the class now includes the
getFloat()
and nextFloat()
methods.
They generate random float values.unserialize()
error handling. In previous versions, it
would sometimes emit an E_NOTICE
.range()
function. It includes new error and
warning behaviors for certain types of inputs.zend.max_allowed_stack_size
and
zend.reserved_stack_size
. This aims to make debugging
easier by preventing stack-overflow-induced segmentation
faults.You can find the full list of new features in the release notes.
The first step to harnessing the power of PHP 8.3 is to upgrade your current PHP environment to version 8.3. This upgrade is crucial for accessing the new features and performance improvements. By upgrading to 8.3, you can enjoy a performance increase of up to 42%, depending on your stack.
For guidance on how to upgrade, please see the official migration guide. Be mindful of any breaking changes that might be applicable to your app.
The new syntax and type safety features can significantly enhance the developer experience. This boosts performance as developers can rapidly identify and address performance issues. Here are some examples of leveraging the new features for a faster development cycle.
Example 1: Using Typed Class Constants
Typed class constants ensure that your code uses constants correctly throughout your application. This feature can prevent runtime errors. It's especially helpful in critical areas like caching. As a result, it makes your app more stable and faster.
class CacheSettings {
public const int MAX_LIFETIME = 3600; // Typed as integer
// ... other constants
}
// Usage
$cacheLifetime = CacheSettings::MAX_LIFETIME;
Example 2: Ensuring Correct Method Overrides with #[\Override]
class BaseClass {
public function compute() {
// Base implementation
}
}
class ChildClass extends BaseClass {
#[\Override]
public function compute() {
// Correctly overridden method
}
}
In PHP 8.3, you apply the #[\Override] attribute to child class methods. It
ensures that the compute()
method in
ChildClass
overrides its parent in
BaseClass
. This prevents bugs and maintains
performance integrity in complex class hierarchies.
Example 3: Improved Error Handling
try {
// Code that may throw an exception
} catch (FirstException | SecondException $e) {
// Handle multiple exceptions
}
PHP 8.3 can catch many exceptions in a single block. It streamlines error handling, saving time, and reducing code complexity.
Example 4: Extended Type Support
function addNumbers(int|float $a, int|float $b): int|float {
return $a + $b;
}
PHP 8.3 enhances its type system by introducing extended type support. Extended type support includes using union types in function signatures. The code above demonstrates this feature. It allows variables and return types to accept multiple types. Here, parameters and the return value can be either integers or floats. This offers greater flexibility and precision. This enhancement leads to clearer, self-documenting code, reducing type-related bugs. PHP 8.3 allows more precise and flexible function definitions. This improves code robustness and versatility. It also aids in the early detection of type-related errors. This contributes to application stability and efficiency.
In PHP 8.3, the new json_validate() function simplifies validating JSON data. Before, developers had to rely on custom validation logic or external libraries. This was time-consuming and error-prone. Now you use json_validate() to check the format and structure of JSON strings. It's a single function call. This function streamlines JSON data handling. It is especially helpful in applications that use JSON a lot, like APIs. It reduces complexity and improves code reliability.
Previous PHP versions:
function json_validate(string $string): bool {
json_decode($string);
return json_last_error() === JSON_ERROR_NONE;
}
var_dump(json_validate('{ "test": { "foo": "bar" } }')); // true
PHP 8.3:
var_dump(json_validate('{ "test": { "foo": "bar" } }')); // true
You can further boost performance of your apps by using the following strategies. These strategies optimize other layers of your application stack. They ensure a comprehensive approach to performance improvement.
Implementing caching strategies is crucial for reducing server load. It also speeds up response times.
HTTP/2 introduces a multitude of improvements over HTTP/1.1, most notably:
Database interactions are often the bottleneck in web applications. Optimizing them can yield significant performance gains.
By focusing on these areas, you can greatly enhance your PHP applications. But, you might be wondering, "how do I find out where the bottlenecks are in the first place?" That’s where Application Performance Monitoring (APM) comes in!
Application Performance Monitoring (APM) tools offer invaluable insights into your application's performance.
Real-time monitoring in APM tools can help you make your PHP application faster. It involves the continuous observation and analysis of an application's performance metrics.
This process includes tracking critical metrics. These metrics are response times, memory usage, server load, and database query efficiency. These metrics allow quick identification of performance bottlenecks. Performance bottlenecks are parts of the application where performance is poor. By detecting these issues in real-time, you can rapidly diagnose and address them. This reduces downtime and enhances user experience.
An example of an APM tool that provides this capability is Scout APM. It specifically offers real-time monitoring for PHP applications. Scout enables developers to identify and fix performance-related issues as they arise.
Detailed Trace Insights are a crucial feature in APM tools. They provide in-depth application analysis.
This feature provides detailed insight into the execution of specific requests or transactions. It allows you to trace the journey of a request from start to finish. It breaks down the process into individual components and operations. The details reveal the precise line of code or database query causing performance issues.
With these insights, APMs enable developers to identify and rectify inefficiencies or errors. Enabling you to fine-tune your app for optimal performance.
PHP 8.3 is not just another update; it's a transformational shift in how PHP powers web applications. You should embrace PHP 8.3 and follow the performance enhancement tips outlined here. Doing this ensures that your app runs faster and more efficiently. Additionally, your users will enjoy a superior user experience. Finally, integrate APM tools like Scout APM into your workflow. APM tools will further streamline your development process and improve your app's performance.
The post Make your app faster with PHP 8.3 appeared first on Laravel News.
Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.
Read more https://laravel-news.com/make-your-app-faster-with-php-83
Read more https://build.prestashop-project.org/news/2024/core-monthly-2024-01-01-2024-01-31/
The once()
function was originally inspired by
this tweet by Taylor Otwell, made into a
package by Spatie, and now finds its way into the core
of Laravel framework in Laravel
11.
This helper ensures that you'll always get the same value no matter how many times you call an object method. The once function is helpful when you have some code that you want to ensure only ever runs one time.
Let’s use the new Laravel 11 make:class
Artisan
command to demonstrate how it works:
php artisan make:class OnceDemo
Here’s the OnceDemo
code that demonstrates how
memoization works:
<?php
namespace App;
use Illuminate\Support\Str;
use Ramsey\Uuid\UuidInterface;
class OnceDemo
{
public function uuid(): UuidInterface
{
return Str::uuid();
}
public function uuidOnce(): UuidInterface
{
return once(fn (): UuidInterface => $this->uuid());
}
}
If you run the following PHP code without using the
once()
helper, you’ll get a new UUID with each method
call:
$demo = new App\OnceDemo;
foreach (range(1,5) as $_) {
echo $demo->uuid() . "\n";
}
/*
9ee5dc3c-f34b-4424-827d-13b662bb0ce1
ad9cca9d-4e98-4307-994c-c610df7c70ac
d642bc9e-d8bb-4bfe-a647-78b555b22e1c
7968b5f2-80f4-40de-95e0-e1f576c37e60
78b69cbb-07b3-45a4-b77b-edefb16f2782
*/
However, if you run the same code using the once()
helper, you’ll get the same result each time:
$demo = new App\OnceDemo;
foreach (range(1,5) as $_) {
echo $demo->uuidOnce() . "\n";
}
/*
5cdfa44b-5ae5-4b0f-8a6f-4b167307fa05
5cdfa44b-5ae5-4b0f-8a6f-4b167307fa05
5cdfa44b-5ae5-4b0f-8a6f-4b167307fa05
5cdfa44b-5ae5-4b0f-8a6f-4b167307fa05
5cdfa44b-5ae5-4b0f-8a6f-4b167307fa05
*/
This method will always return the same object instance in our demo example, and you can verify this behavior:
$demo = new App\OnceDemo;
foreach (range(1,5) as $_) {
echo spl_object_id($demo->uuidOnce()) . "\n";
}
/*
5075
5075
5075
5075
5075
*/
When running tests, the memoization function must be cleared
after each test to ensure you are working in a pristine state.
Laravel takes care of this detail for you in the base
TestCase
class using the Once::flush();
method.
Shout out to Nuno Maduro, who implemented this feature in Pull Request #49744!
The post The once() Memoization Helper is Coming to Laravel 11 appeared first on Laravel News.
Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.
Read more https://laravel-news.com/once-helper