Named arguments in PHP 8

Thu 23, Jul 2020

Hi!

One of the coolest new features of PHP 8 are named arguments (parameters). I'm really happy that they made it into PHP 8, as they're a huge improvement syntax-wise, I think. But first, take a look at what they look like:

class Post {

    public function __construct(
        string $title,
        string $body,
        string $author
    ) {}

}

# ...

$post = new Post(
    title: 'Some interesting post',
    body: 'Bla bla body text here',
    author: 'John'
);

Why?

While this feature was highly debated, I think it comes with far more advantages than disadvantages. It allows for cleaner and easier to understand code (think (min: 0, max: 86400) instead of (0, 86400)). It also allows us to skip default values. Say we have the following function:

function cacheText(
    string $key,
    string $value,
    int $expires = 86400,
    string $directory = 'cache/'
) {}

If we now wanted to call this function with a different directory, but keep $expires with its default value, we can now write this

cacheText(
    key: 'content-home',
    value: 'something bla bla',
    directory: 'someOtherDir/'
);

instead of that:

cacheText(
    'content-home',
    'something bla bla',
    86400,
    'someOtherDir/'
);

Named arguments can also be used together with ordered arguments. That means that you could, for example, write this:

$post = new Post(
    'Some interesting post',
    body: 'Bla bla body text here',
    author: 'John'
);

What would not work, however, is doing it this way:

$post = new Post(
    title: 'Some interesting post',
    'Bla bla body text here',
    author: 'John'
);

You can only use ordered arguments together with named ones at the beginning of the argument list. If you're using ordered arguments between named ones, PHP throws an error.

Named arguments are also supported in annotations/attributes, by the way!

In case you want some more info on that, view this article and the RFC!

PHP 8 Attribute Syntax

Thu 02, Jul 2020

So @@ reaches the quota and has been elected as the final attribute syntax for PHP 8.

@@ will be the attribute syntax for PHP 8:

@@SomeAttribute
class Something {}

I personally think that choosing @@ was the right decision.

If you don't really know what's going on with those attributes, read this!

Source

Add CSS to a page using HTTP headers

Tue 28, Apr 2020

Hey y'all,

I just read about the Link header at Impressive Webs. It works just like the <link> HTML tag. That means that you can use it to add stylesheets to a website! Below is a PHP-based demo:

The page:

<?php
header('Link: <styles.css>; rel=stylesheet');
echo '<p>Some text here. This will get displayed using a sans-serif font if your browser supports the Link header. If not, your browser\'s default font will be used.</p>';

The stylesheet (named styles.css):

html,
body {
    font-family: sans-serif
}

The header will look like this:

Link: <styles.css>; rel=stylesheet

You can add multiple stylesheets by adding multiple Link headers, btw.

Browser support

Even though this is a standardized feature that has been around since HTML4, it seems to work in Firefox only. It is not deprecated, though. This is what the HTML4 spec says about it:

This section only applies to user agents conforming to versions of HTTP that define a Link header field. Note that HTTP 1.1 as defined by [RFC2616] does not include a Link header field (refer to section 19.6.3).

Why bother if it's only supported in Firefox?

I think it's just something really cool to look at. If you use it in a project, I'd highly recommend you to use <link> in addition, because otherwise most users probably won't see your stylesheets.

If you want to find out more about it, I'd highly recommend you to read this article at Impressive Webs and look at the Link header's MDN page.

New in PHP: str_contains

Mon 16, Mar 2020

RFC str_contains has been merged into PHP:

str_contains checks if a string is contained in another string and returns a boolean value (true/false) whether or not the string was found.

It's basically just a shorter way of writing strpos($haystack, $needle) !== false. It will be available in PHP 8.

Example (taken from the RFC page):

str_contains('abc', 'a'); // true
str_contains('abc', 'd'); // false

// $needle is an empty string
str_contains('abc', '');  // true
str_contains('', '');     // true

JSON responses, redirects and cookies in Sierra

Mon 09, Mar 2020

Please note that this article refers to a very old version of Sierra. This does not work anymore with newer versions of it!

Just wanted to show you some cool new features in Sierra:

  1. JSON responses
  2. Redirect responses
  3. Cookies

JSON responses

Just create a new Sierra\HTTP\JSONResponse and pass it some data:

>?php
use Sierra\MVC\Controller;
use Sierra\HTTP\JSONResponse;

class Home extends Controller {

    public function index() {
        new JSONResponse(array(
            'hello' => 'world'
        ));
    }

}

Redirect responses

Redirecting a user has never been easier:

>?php
use Sierra\MVC\Controller;
use Sierra\HTTP\RedirectResponse;

class Home extends Controller {

    public function index() {
        # Will redirect the user to /new/target/
        new RedirectResponse('/new/target/');
    }

}

Constructing this class will also print some HTML containing a .

Cookies

Cookies can now be set using $this->res->set_cookie() in controllers:

>?php
use Sierra\MVC\Controller;
use Sierra\HTTP\Cookie;

class Home extends Controller {

    public function index() {
        $this->res->set_cookie(new Cookie('name', 'value'));
        echo 'Cookie has been set!';
    }

}

Releasing my PHP framework

Fri 06, Mar 2020

Hi!

I've just released my PHP MVC framework on GitHub. It's a rewrite with a lot of newly added extensions of the framework I'm using on this and many other sites.

You can check it out at sierra-project/sierra. Feedback is highly appreciated! :)

Lazy loading images in Parsedown

Thu 13, Feb 2020

Parsedown is probably the most used Markdown engine for PHP (it also powers this site!). I wanted to integrate loading="lazy" into Parsedown, as it's now part of the HTML standard.

This is my approach:

class ParsedownLL extends Parsedown {

    protected function inlineImage($excerpt) {
        $image = parent::inlineImage($excerpt);

        if (!isset($image)) {
            return null;
        }

        $image['element']['attributes']['loading'] = 'lazy';

        return $image;
    }

}

Keep in mind to use ParsedownLL instead of Parsedown, but include both.

Native lazy loading is part of the HTML specification

Thu 13, Feb 2020

Loading images just as soon as they get into the viewport has been a thing for some time. It is used for performance reasons, as the page loads faster this way. There was no way to do this with plain HTML, though. Now there is! Chrome's loading attribute on <img> tags has made it into the HTML standard.

All you have to do to lazy load an image:

<img src="..." alt="..." loading="lazy">

Keep in mind that only a small number of browsers actually support this feature at the moment!

HTRoute v0.1.0

Sat 01, Feb 2020

Note: this project has been obsolete for quite some time now. Consider using Express instead!

Hi!

I'm very excited to release my Node.js HTTP routing library HTRoute (HyperTextRoute). Its goals are to be very easy to use and to provide very good routing functionality while mainting a small overall package size and absolutely amazing speed.

Examples and some docs are available in its GitHub repository.

Feedback and bug reports are very appreciated! :)

YouTube-like page loading bar animation in CSS

Sat 04, Jan 2020

Thought this might be worth sharing.

The animation

I just figured out how to create that YouTube loading bar at the top of the page. It's actually really simple! Here's how:

The HTML is just one element:

<div class="anim"></div>

The CSS:

html,
body {
    z-index: 0;
    margin: 0 auto;
}

.anim {
    z-index: 1000;
    animation-name: fill;
    animation-duration: 1s;
    background-color: red;
}

@keyframes fill {
    0% {
        width: 0%;
        padding: 2px;
    }

    75% {
        width: 100%;
        padding: 2px;
    }

    100% { padding: 0px; }
}

You are on page 1 right now.


Back to top