Matthias NobackIs all code in vendor infrastructure code? (22.2.2020, 09:15 UTC)

During a recent run of my Advanced Web Application Architecture training, we discussed the distinction between infrastructure code and non-infrastructure code, which I usually call core code. One of the participants summarized the difference between the two as: "everything in your vendor directory is infrastructure code". I don't agree with that, and I will explain why in this article.

Not all code in vendor is infrastructure code

Admittedly, it's easy for anyone to not agree with a statement like this, because you can simply make up your own definitions of "infrastructure" that turn the statement false. As a matter of fact, I'm currently working on my next book (which has the same title as the training), and I'm working on a memorable definition that covers all the cases. I'll share with you the current version of that definition, which consists of two rules defining core code. Any code that doesn't follow both these rules at the same time, should be considered infrastructure code.

Rule 1: Core code doesn't directly depend on external systems, nor does it depend on code written for interacting with a specific type of external system.

Rule 2: Core code doesn't need a specific environment to run in, nor does it have dependencies that are designed to run in a specific context only.

Following this definition means that as soon as a piece of code reaches out to something outside of the running application (e.g. it connects to the network, touches the file system, requests the current time or random data), it should be considered infrastructure code. As soon as a piece of code could only runs in a particular environment (a web application, a CLI application, etc.) it should also be considered infrastructure code.

These rules don't say anything about whether core code lives in src/ or in vendor/, and rightfully so. Imagine you have a piece of code you are allowed to call core code because it matches its definition. If you now move this code to a separate repository on GitHub, publish it as a package, and install it in your project's vendor/ directory with Composer, would that same piece of code suddenly become infrastructure code? Of course not. The location of code doesn't determine what kind of code it is.

So whether or not something is vendor code doesn't determine if it's infrastructure code. What makes the difference is whether or not you can run that code in complete isolation, without making external dependencies available, and without preparing the environment in some way.

Unit tests and core code

This may remind you of Michael Feather's definition of a unit test:

A test is not a unit test if:

  • It talks to the database
  • It communicates across the network
  • It touches the file system
  • It can't run at the same time as any of your other unit tests
  • You have to do special things to your environment (such as editing config files) to run it.

Tests that do these things aren't bad. Often they are worth writing, and they can be written in a unit test harness. However, it is important to be able to separate them from true unit tests so that we can keep a set of tests that we can run fast whenever we make our changes.

In fact, following my definition of core code, we can conclude that core code is the only code that can be unit tested. This doesn't mean that you can't test infrastructure code, it only means that such a test could not be considered a unit test. These tests are often called integrated or integration tests instead.

Most, but not all code in vendor is infrastructure code

So there is no strict relation between being-infrastructure-code and being-inside-the-vendor-directory. However there is somewhat of an inverse relation: much of your application's infrastructure code lives in your vendor directory. You could also say that you write most of the core code yourself.

Let's take a look at some examples of code that lives in vendor, but would (according to my rules) not be called infrastructure code:

  • An event dispatcher library
  • An assertion library
  • A value object library

Libraries that only deal with transforming data (like some kind of data transformer, mapper, or serializer) could be considered non-infrastructure code as well.

In practice, you can use the following checklist to find out if code (wherever it lives, in src or vendor)

Truncated by Planet PHP, read more at the original (another 1256 bytes)

Link
Evert PotTypescript is changing how I write code (21.2.2020, 20:14 UTC)

Typescript is not just Javascript + types. Using TS more is slowly altering how I think about how my code should be written. My code is becoming more functional, and I’m incentivized to write things in a way that typescript is more likely to catch.

I wanted to share an isolated example of this.

In this example we need to process a chat message. This message can be either the type ‘text’, ‘picture’, or ‘video’. After this process is complete, I’m returning an ‘id’.

In the past, this is how I would have handled it:

function processMessage(message) {

  switch(message.type) {

    case 'text' :
      return processText(message); 
    case 'picture' :
      return processPicture(message);
    case 'video' :
      return processVideo(message);
    default :
      throw new Error('Unknown message type: ' + message.type);

  }

}

A direct translation to Typescript might look like this:

type Message = {
  type: 'text' | 'picture' | 'video',
  sender: string;
}


function processMessage(message: Message): number {

  switch(message.type) {

    case 'text' :
      return processText(message); 
    case 'picture' :
      return processPicture(message);
    case 'video' :
      return processVideo(message);
    default :
      throw new Error('Unknown message type: ' + message.type);

  }

}

Truncated by Planet PHP, read more at the original (another 4465 bytes)

Link
Derick RethansPHP Internals News: Episode 41: __toArray() (20.2.2020, 09:04 UTC)

PHP Internals News: Episode 41: __toArray()

In this episode of "PHP Internals News" I chat with Steven Wade (Twitter, GitHub, Website) about the __toArray() RFC.

The RSS feed for this podcast is https://derickrethans.nl/feed-phpinternalsnews.xml, you can download this episode's MP3 file, and it's available on Spotify and iTunes. There is a dedicated website: https://phpinternals.news

Transcript

Derick Rethans 0:16

Hi, I'm Derick. And this is PHP internals news, a weekly podcast dedicated to demystifying the development of the PHP language. Hi, this is Episode 41. Today I'm talking with Stephen Wade about an RFC that he's produced, called __toArray(). Hi, Steven, would you please introduce yourself?

Steven Wade 0:35

Hi, my name is Steven Wade. I'm a software engineer for a company called follow up boss. I've been using PHP since 2007. And I love the language. So I wanted to be able to give back to it with this RFC.

Derick Rethans 0:48

What brought you to the point of introducing this RFC?

Steven Wade 0:50

This is a feature that I've I've kind of wish would have been in the language for years, and talking with a few people who encouraged it's kind of like the rule of starting a user group right? If there's not one and you have the desire, then you're the person to do it. A few people encouraged and say: Well, why don't you go out and write it. So I've spent the last two years kind of trying to work up the courage or research it enough or make sure I write the RFC the proper way, and then also actually have the time to commit to writing it and following up with any of the discussions as well.

Derick Rethans 1:18

Okay, so we've mentioned the word RFC a few times. But we haven't actually spoken about what it is about. What are you wanting to introduce into PHP?

Steven Wade 1:25

I want to introduce a new magic method. The as he said, the name of the RFC is the __toArray(). And so the idea is that you can cast an object, if your class implements this method, just like it would toString(). If you cast it manually to array then that method will be called if it's implemented. Or as, as I said, in the RFC, array functions will it can it can automatically cast that if you're not using strict types.

Derick Rethans 1:49

Oh, so only if it's not strictly typed. So if its weakly typed would call the toArray() method if the function's argument or type hint array.

Steven Wade 1:58

Yes, and that is actually something that came up during the discussion period, which is something again, this is why we have discussions, right? Is to kind of solicit feedback on things we don't think about it, we may overlook or, and so someone did point out that it is, you know, it would not function that way, or you would not expect it to be automatically cast for you, if you're using strict types.

Derick Rethans 2:17

Okay.

Steven Wade 2:18

The RFC has been updated to reflect that as well.

Derick Rethans 2:20

So now the RFC says it won't be automatically called just for type hint.

Steven Wade 2:24

Correct.

Derick Rethans 2:24

Not everybody is particularly fond of magic methods. What would you say about the criticism that introducing even more of them would be sort of counterproductive,

Truncated by Planet PHP, read more at the original (another 16164 bytes)

Link
PHP: Hypertext PreprocessorPHP 7.2.28 Released (20.2.2020, 00:00 UTC)
The PHP development team announces the immediate availability of PHP 7.2.28. This is a security release.All PHP 7.2 users are encouraged to upgrade to this version.For source downloads of PHP 7.2.28 please visit our downloads page, Windows source and binaries can be found on windows.php.net/download/. The list of changes is recorded in the ChangeLog.
Link
PHP: Hypertext PreprocessorPHP 7.4.3 released (20.2.2020, 00:00 UTC)
The PHP development team announces the immediate availability of PHP 7.4.3. This is a security release which also contains several bug fixes.All PHP 7.4 users are encouraged to upgrade to this version.For source downloads of PHP 7.4.3 please visit our downloads page, Windows source and binaries can be found on windows.php.net/download/. The list of changes is recorded in the ChangeLog.
Link
PHP: Hypertext PreprocessorPHP 7.3.15 Released (20.2.2020, 00:00 UTC)
The PHP development team announces the immediate availability of PHP 7.3.15. This is a security release which also contains several bug fixes.All PHP 7.3 users are encouraged to upgrade to this version.For source downloads of PHP 7.3.15 please visit our downloads page, Windows source and binaries can be found on windows.php.net/download/. The list of changes is recorded in the ChangeLog.
Link
platform.shPHPun with FFI: Just enough C (20.2.2020, 00:00 UTC)
One of the new and exciting features of PHP 7.4 is its support for Foreign Function Interface, or FFI. FFI provides a much easier way to load code from other, faster languages into PHP than writing an extension. That said, easier doesn’t mean trivial. There is some work involved, and it’s not appropriate in all situations. Anatomy of a C library The most common language for FFI integration is C, in part because of its ubiquity and in part because it’s the most common language for people who want to squeeze the most performance out of their computer.
Link
Evert Pot (19.2.2020, 20:04 UTC)
Link
Evert PotImplementing an opaque type in typescript (18.2.2020, 18:30 UTC)

Say, you’re in a situation where you have a user type, that looks a bit as follows:

export type User = {
  firtName: string;
  lastName: string;
  email: string;
}

function save(user: User) {
   // ...
}

const user = {
  firstName: 'Evert',
  lastName: 'Pot',
  email: 'foo@example.org',
}

save(user);

But, instead of accepting any string for an email address, you want to ensure that it only accepts email addresses that are valid.

You might want to structure your user type as follows:

type Email = string;

export type User = {
  firtName: string;
  lastName: string;
  email: Email
}

This doesn’t really do anything, we aliased the Email to be exactly like a string, so any string is now also an Email.

We can however extend the email type slighty to contain a property that nobody can ever add.

declare const validEmail: unique symbol;

type Email = string & {
  [validEmail]: true
}

export type User = {
  firstName: string;
  lastName: string;
  email: Email
}

In the above example, we’re declaring a symbol. This is similar to using const validEmail = Symbol('valid-email');, but it doesn’t exist after compiling.

The unqiue symbol type is a type that can never be created.

We’re adding a property with this key to our Email string. A user can only add this property, if they have an exact reference to the original symbol.

Given that we don’t export this symbol, it’s not possible anymore for a user to construct an Email type manually.

Now when we compile this:

const 

Truncated by Planet PHP, read more at the original (another 12831 bytes)

Link
Rob AllenValidating default PHP session ID values (13.2.2020, 11:00 UTC)

I recently needed to validate the value created by PHP for its session ID. After a bit of research, I realised that there are two interesting php.ini config settings that relate to this value:

  • session.sid_length is the number of characters in the ID
  • session.sid_bits_per_character controls the set of characters used. From the manual:

    The possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ",").

Therefore, to validate the session ID we need to create a regular expression that looks for the correct set of characters of the expected length.

I wrote function to do this:

function isValidSessionId(string $sessionId): bool
{
    $sidLength = ini_get('session.sid_length');

    switch (ini_get('session.sid_bits_per_character')) {
        case 6:
            $characterClass = '0-9a-zA-z,-';
            break;
        case 5:
            $characterClass = '0-9a-z';
            break;
        case 4:
            $characterClass = '0-9a-f';
            break;
        default:
            throw new \RuntimeException('Unknown value in session.sid_bits_per_character.');
    }
    $pattern = '/^[' . $characterClass . ']{' . $sidLength . '}$/';

    return preg_match($pattern, $sessionId) === 1;
}

You could use it like this:

$name = session_name();
if (isset($_COOKIE[$name])) {
    if (!isValidSessionId($_COOKIE[$name])) {
        // invalid - return an error, just send back a 500 or something
        exit;
    }
}

As far as I can tell, we can't use session_id() as we haven't started the session yet, however as the session is just a cookie at the HTTP level, we can use $_COOKIE instead.

Note also that the manual has an excellent section on Sessions and Security which is worth reading.

Link
LinksRSS 0.92   RDF 1.
Atom Feed   100% Popoon
PHP5 powered   PEAR
ButtonsPlanet PHP   Planet PHP
Planet PHP