Paul M. Jones

Don't listen to the crowd, they say "jump."

Symfony 4: Directory Structure, and Common Practices

Fabien has published his plans for the new Symfony 4 directory structure. Not that it matters much to anyone in Symfony-land, where I have no status that I’m aware of, but I am happy to see the changes described.

Having said that, and recognizing that Fabien obviously has final say over his own projects …

The new etc/ directory is the equivalent of the current app/config/ directory.

Web files under web/

… it might be nice if Symfony 4 adopted more existing common practices, used by roughly 70% of Packagist packages. That is, to use config/ for the top-level config directory, and public/ for the top-level document-root directory.

More specifically:

  • config/ is used ~10x more than etc/ (ref)

  • public/ is used ~2x more than web/ (ref)

As a side note, that research resulted in the pds/skeleton publication.

(This blog post originated as a comment on Reddit.)


A 4-Part System for Understanding How the World Works

Via Lion of the Blogosphere.:

  1. Human biodiversity (HBD):
    • Differences between races.
    • Differences between men and women.
    • Biological/evolutionary basis for behavior.
  2. Value transference. … [In] a post-scarcity economy, the majority of work is value transference work, work that doesn’t create any value but just transfers the value created by others.
  3. Relative wants. …This is also related to our desire for status.
  4. Religion and groupthink. … [Religion is] “A cultural system of beliefs, behaviors, practices, ethics and societal organization that relate humanity to an order of existence.” Groupthink is the tendency for people to believe whatever other people believe.

Command-Line Output: Consider Logging Over Streams

When writing command-line applications for PHP, consider using a logger for screen output. This is something I've done with great success in several projects. Producer, for example, uses a very light standard I/O logger class that writes output to STDOUT and STDERR resource/stream handles. Every command that generates output uses that standard I/O logger (cf. the issues command).

This has a couple of advantages:

  • Your command-line code gets stdout/stderr output separation practically for free, using a common PSR-3 interface.

  • If you incorporate that command-line tool into another class, you can easily inject a different PSR-3 logger so that output is captured elsewhere, instead of writing to stdout/stderr. Among other things, that makes it relatively easy to test the output of your command-line code without having to use output buffering.

I think this approach works best for non-interactive commands. If you have to read keyboard input from the user as part of the command, using a logger for output might not make a lot of sense. But if all of the command inputs are handled as options or flags, using a logger for output can be great.


Regarding A Recent Event

KING HENRY V: We judge no less. Uncle of Exeter,
    Enlarge the man committed yesterday,
    That rail'd against our person: we consider
    it was excess of wine that set him on;
    And on his more advice we pardon him.

SCROOP: That's mercy, but too much security:
    Let him be punish'd, sovereign, lest example
    Breed, by his sufferance, more of such a kind.

KING HENRY V: O, let us yet be merciful.

CAMBRIDGE: So may your highness, and yet punish too.

GREY: Sir,
    You show great mercy, if you give him life,
    After the taste of much correction.

KING HENRY V: Alas, your too much love and care of me
    Are heavy orisons 'gainst this poor wretch!
    If little faults, proceeding on distemper,
    Shall not be wink'd at, how shall we stretch our eye
    When capital crimes, chew'd, swallow'd and digested,
    Appear before us? We'll yet enlarge that man,
    Though Cambridge, Scroop and Grey, in their dear care
    And tender preservation of our person,
    Would have him punished. And now to our French causes:
    Who are the late commissioners?

CAMBRIDGE: I one, my lord:
    Your highness bade me ask for it to-day.

SCROOP: So did you me, my liege.

GREY: And I, my royal sovereign.

KING HENRY V: Then, Richard Earl of Cambridge, there is yours;
    There yours, Lord Scroop of Masham; and, sir knight,
    Grey of Northumberland, this same is yours:
    Read them; and know, I know your worthiness.
    My Lord of Westmoreland, and uncle Exeter,
    We will aboard to night. Why, how now, gentlemen!
    What see you in those papers that you lose
    So much complexion? Look ye, how they change!
    Their cheeks are paper. Why, what read you there
    That hath so cowarded and chased your blood
    Out of appearance?

CAMBRIDGE: I do confess my fault;
    And do submit me to your highness' mercy.

GREY    |
        | To which we all appeal.
SCROOP  |

KING HENRY V: The mercy that was quick in us but late,
    By your own counsel is suppress'd and kill'd:
    You must not dare, for shame, to talk of mercy;
    For your own reasons turn into your bosoms,
    As dogs upon their masters, worrying you.

I hope this is the last thing I will have to say on the matter.


WikiMedia, Clean Architecture, and ADR

tl;dr: Action-Domain-Responder is a natural fit for the HTTP user-interface portions of Clean Architecture (or Hexagonal), especially with Domain Driven Design. Just be sure to remember to separate the HTTP response presentation from the action code.


I.

Jeroen de Dauw has a fantastic post on Implementing the Clean Architecture in PHP, with Domain Driven Design elements. You should read the whole thing, and examine the implementation codebase, for a number of useful insights. Though I might quibble over some elements of the implementation, I think it is a good offering, and serves as a solid reference point.

In his article, Jeroen notes they are using Silex for their HTTP user-interface system, and describes the logic of each route action:

Inside this [Silex action] we construct our framework agnostic request model and invoke the Use case with it. Then we hand over the response model to a presenter to create the appropriate HTML or other such format.

That is a very near paraphrase of Action-Domain-Responder:

  • The Action marshals input from the HTTP request
  • The Action invokes a Domain element with that input and gets back a result
  • The Action passes that result to a Responder to build the HTTP response

In Jeroen’s implementation, each Action is a closure defined in the routes.php file. The Action marshals input from the HTTP request using a “request model” (an input object tailored to the domain) and passes it to a “use case.” Each “use case” is an entry point into the Domain, and returns a “response model” (the domain result).

The only place where Jeroen’s implementation deviates from ADR is that the Action code builds the presentation itself, instead of handing off to a Responder. (This may be a result of adhering to the idioms and expectations specific to Silex.)

Because the rest of the implementation is so well done, refactoring to a separated presentation in the form of a Responder is a straightforward exercise. Let’s see what that might look like.

II.

First, as an example, review the code in the check-iban action. The following reorganization of that action code makes the ADR pattern more obvious:

<?php
$app->get(
    'check-iban',
    function( Request $request ) use ( $app, $ffFactory ) {

        // marshal input
        $input = new Iban( $request->query->get( 'iban', '' ) );

        // invoke domain and get back result
        $result = $ffFactory->newCheckIbanUseCase()->checkIban($input);

        // presentation
        return $app->json(
            $ffFactory->newIbanPresenter()->present( $result )
        );
    }
);
?>

Very clear and straightforward. However, the presentation work is embedded in the action with the $app->json(...) call. (My guess is that’s probably a result of working with existing Silex idioms.)

Another good example is the list-comments.html action. Reorganizing the logic to make the ADR pattern more obvious gives us the following:

<?php
$app->get(
    'list-comments.html',
    function( Request $request ) use ( $app, $ffFactory ) {

        // marshal input
        $input = new CommentListingRequest(
            10,
            (int)$request->query->get( 'page', '1' )
        );

        // invoke domain and get back result
        $result = $ffFactory
            ->newListCommentsUseCase()
            ->listComments( $input );

        // presentation
        return new Response(
            $ffFactory->newCommentListHtmlPresenter()->present(
                $result,
                (int)$request->query->get( 'page', '1' )
            )
        );
    }
);
?>

Again, the presentation work is embedded in the action code.

In general, it is better to completely separate the presentation work from the action code. Remember that in an HTTP context, the presentation is not just the body of the HTTP response. Instead, the presentation is the entire HTTP response, including headers and status. (For more on this, see The Template Is Not The View.)

With the above examples, because they are already so well structured, it would be easy to extract the presentation to a Responder class. For example, the list-comments action could have the presentation work completely removed like so:

<?php
// hypothetical class with the extracted logic
class ListCommentsHtmlResponder
{
    public function buildResponse($request, $result, $ffFactory)
    {
        return new Response(
            $ffFactory->newCommentListHtmlPresenter()->present(
                $result,
                (int)$request->query->get( 'page', '1' )
            )
        );
    }
}

// the refactored action code
$app->get(
    'list-comments.html',
    function( Request $request ) use ( $app, $ffFactory ) {

        // marshal input
        $input = new CommentListingRequest(
            10,
            (int)$request->query->get( 'page', '1' )
        );

        // invoke domain and get back result
        $result = $ffFactory->newListCommentsUseCase()->listComments($input);

        // hand result to responder
        return $ffFactory->newListCommentsHtmlResponder()->buildResponse(
            $request,
            $result,
            $ffFactory
        );
    }
);
?>

Now the presentation work of building an HTTP response is cleanly separated from the rest of the action code.

III.

When separating concerns along these lines, you begin to see the similarities in the presentation work, and can start to reduce repetition across the codebase. For example, any Action that delivers a JSON response might use the same base JSON Responder.

Eventually, you may realize that the logic of each action is effectively identical. That is, you always collect input, pass that input through the domain to get back a result, and pass that result to a response builder.

When that realization occurs, you can build a single action handler that coordinates between injected input marshals, domain entry points, and response builders. That’s exactly what the Arbiter ActionHandler does, and Radar uses that in turn to specify the input + domain + responder callables for each route.

At that point, you are out of the business of writing action methods entirely. Then the user-interface code can focus on marshaling inputs going to the domain, and on presenting the results coming out of the domain – which is exactly how things should be.

P.S.

Jeroen’s writeup also reveals that at least some of the elements in his implementation are returning something like Domain Payload objects. Cf. the ValidationResult class, used in the validate-payment-data action among other places.

I’m a big fan of the Domain Payload pattern in ADR, and using a Domain Payload for all returns received by the action code. Doing so simplifies the response-building logic even further; for example, by collecting common “success” and “failure” presentation work across different JSON responders.

Then there’s this bit about containers:

We decided to go with our own top level factory, rather than using the dependency injection mechanism provided by Silex: Pimple. Our factory internally actually uses Pimple, though this is not visible from the outside. With this approach we gain a nicer access to service construction, since we can have a getLogger() method with LoggerInterface return type hint, rather than accessing $app[‘logger’] or some such, which forces us to bind to a string and leaves us without type hint.

This resonates with some other ideas I’ve been toying with, namely that the user-interface container might better be separated from the domain container. They can be wired up separately from each other, making it easier to package the Domain portions independently from the user-interface portions, and enforcing a “physical” boundary between the two.

Overall, congratulations to Jeroen on putting together such a good writeup.


Who Rules the United States?

The last few weeks have confirmed that there are two systems of government in the United States. The first is the system of government outlined in the U.S. Constitution--its checks, its balances, its dispersion of power, its protection of individual rights. Donald Trump was elected to serve four years as the chief executive of this system. Whether you like it or not.

The second system is comprised of those elements not expressly addressed by the Founders. This is the permanent government, the so-called administrative state of bureaucracies, agencies, quasi-public organizations, and regulatory bodies and commissions, of rule-writers and the byzantine network of administrative law courts. This is the government of unelected judges with lifetime appointments who, far from comprising the "least dangerous branch," now presume to think they know more about America's national security interests than the man elected as commander in chief.

Source: Who Rules the United States?


Radar Project Skeleton Now Stable

I am happy to announce that the project skeleton for Radar, an Action-Domain-Responder system for PHP, is now stable and available for use.

One significant difference between this release and the last alpha is that it now uses the standard pds/skeleton names for directories. Existing Radar projects will not need to change directory names, but be aware that starting a new project with the 1.0.0 version will use "public/" instead of "web/".

Many thanks to everyone who contributed to this release, especially Jake Johns, who put together a post-create-project command to "clean up" the initial installation.


The "pds/skeleton" Standard Is Now Stable!

I am proud to announce that the first PHP Package Development Standards publication, pds/skeleton, has been released as stable at version 1.0.0.

This publication has been a great working effort. Everything from researching first a subset (and then the entirety) of Packagist, to putting together the first drafts, to working with reviewers and refining the publication, has been a wonderful experience. From the first uncommitted work in early Nov 2016, to the stable release a few days ago, the whole process has taken just about 12 weeks of evening and weekend time.

Many thanks to the early reviewers (you know who you are!) for your input, criticism, and suggestions. Thanks also to the issue submitters and commenters, and especially to to everyone who submitted a pull request. These people contributed serious effort and attention to the publication, which helps to show that the publication really is a community-based work.

Roughly 78,000 packages already comply with the pds/skeleton standard, although they may not know it. To formally show that your package has adopted the standard, "require-dev" it via Composer, or display a badge on your README.

Although I have a few ideas in mind, what do you think the next PDS publication should focus on? Let me know if you have a particular area of interest.


The Unanswered Question

The question that faces every man is not “what sort of society do I want for myself and my children?” That’s a lie and it has always been a lie. The question is “What are my choices and how do I achieve my preferred option?”

Source: The Unanswered Question | The Z Blog


‘The Mary Tyler Moore Show’ Gave Us a Feminine, Not a Feminist, Icon

What was endearingly feminine, and touching, about Mary Richards was how willingly she acceded to organizing her life around serving others. Always available for advice, or for babysitting, or for a hug, she was poised, graceful, content. She wasn’t interested in shattering barriers but in being nice.

Source: ‘The Mary Tyler Moore Show’ Gave Us a Feminine, Not a Feminist, Icon - Acculturated (Per the blog post just before this, perhaps "nice" is "feminine.")