Paul M. Jones

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

Command Bus and Action-Domain-Responder

Over the past few weeks, different people have asked me where a Command Bus goes in an Action-Domain-Responder system. While I’m not a DDD expert, after brushing up on the subject a little, my answer is: “In the Domain.”

First, let’s recall the three components in ADR:

  • “Action” is the logic that connects the Domain and Responder. It uses the request input to interact with the Domain, and passes the Domain output to the Responder. (The Action is intentionally “dumb”: it should have no logic at all, aside from perhaps the most minimal of ternaries to allow for default input values. If the Action has a conditional, it is doing too much.)

  • “Domain” is the logic to manipulate the domain, session, application, and environment data, modifying state and persistence as needed. (The word “Domain” here is explicitly intended to remind you of “domain logic” and “domain-driven design.”)

  • “Responder” is the logic to build an HTTP response or response description. It deals with body content, templates and views, headers and cookies, status codes, and so on.

Next, let’s see what Command Bus is. There’s a lot written about it elsewhere …

… so I’ll try to sum up here:

  • A “Command” is a typed or named set of inputs (essentially a data-transfer object) that gets sent to a “Command Bus.”

  • The “Command Bus” then hands off the “Command” to a “Command Handler” specific to that “Command”; the “Command Bus” figures out which “Command Handler” to use from the name or type of the “Command.”

  • The “Command Handler” uses the “Command” inputs to perform some sort of activity.

This series of objects is part of an overarching architectural pattern called Command Query Responsibility Segregation (see here and here). Under CQRS, writes (Commands) are handled separately from reads (Queries). Handling a Command modifies data but does not return a result, while handling a Query returns a result but must not modify data.

This means that a Command Bus does not actually return a result for inspection. You dump a Command into the Bus, and you’re done; there’s no checking for errors at that time. To conform to CQRS properly, you have to perform a separate Query in order to determine the result of the Command.

At this point, just from having read the literature on the patterns and concepts, we can see that Command Bus and its related components are part of the domain layer, not part of the user interface layer. With that in mind, it seems like Command Bus is a candidate for the “Domain” portion of Action-Domain-Responder, to be used like this in an Action:

class CreateItemAction
{
    public function __construct(
        CommandBus $domain,
        CommandResponder $responder
    ) {
        $this->domain = $domain;
        $this->responder = $responder;
    }

    public function __invoke(Request $request)
    {
        $input = $request->getParsedBody();
        $command = new CreateItemCommand(
            $input['item_name'],
            $input['item_description']
        );
        $this->domain->handle($command);
        return $this->responder->createResponse();
    }
}

So the Action gets constructed with a CommandBus element as an entry point into the Domain, and with a generic Responder to build the response. At invocation time, the user interface code sends along the current HTTP request; the Action pulls data out of it to create Command to send to the Command Bus, then tells the Responder to create an HTTP response. (Because a Command never returns anything, one Responder should suffice for all Commands in this setup.)

This is straightforward as an minimal case, but I think it avoids at least two substantial issues.

  1. Where does input validation go? (Input validation, or form validation, is separate from domain model validation.)

  2. Where does error handling go? (While a Command might not return anything, the various elements related to CQRS might very well throw exceptions or raise errors.)

In what we think of as server-side MVC, those two concerns might well be placed in the Controller somewhere. Translating a Controller method directly to an Action, that might look something like this:

    public function __invoke(Request $request)
    {
        // get the input and validate it
        $input = $request->getParsedBody();
        if (! $this->validate($input)) {
            // create an "invalid input" response
            return $this->responder->invalid($input);
        }

        // create the command
        $command = new CreateItemCommand(
            $input['item_name'],
            $input['item_description']
        );

        // try the command
        try {
            $this->domain->handle($command);
            // succcess!
            return $this->responder->success();
        } catch (Exception $e) {
            // there was some sort of subsequent failure
            return $this->responder->failure($e);
        }
    }

On consideration, that seems like a lot of extraneous activity in the user interface layer. In ADR, the Action is intentionally supposed to be dumb. It should not be doing anything even remotely interesting, and certainly should not be dealing with any conditional logic.

As such, I say that Command-related activity should be taken out of the Action entirely, and relegated to something like an Application Service or some other Domain entry point. That Service is what should perform the Command-related activity.

Further, while a Command may not return a result, a Service certainly can. This means that the Action can call the Domain and get back a Domain Payload as a result, which can then be passed to the Responder for presentation.

Under that way of thinking, we get something more like this:

class CreateItemAction
{
    public function __construct(
        ItemService $domain,
        CreateItemResponder $responder
    ) {
        $this->domain = $domain;
        $this->responder = $responder;
    }

    public function __invoke(Request $request)
    {
        $input = $request->getParsedBody();
        $payload = $this->domain->create($input);
        return $this->responder->createResponse($payload);
    }
}

class ItemService
{
    public function create(array $input)
    {
        if (! $this->validate($input)) {
            // create an "invalid input" response
            return new InvalidInputPayload($input);
        }

        // create the command
        $command = new CreateItemCommand(
            $input['item_name'],
            $input['item_description']
        );

        // try the command
        try {
            $this->domain->handle($command);
            return new CommandAcceptedPayload();
        } catch (Exception $e) {
            return new CommandRejectedPayload($e);
        }
    }
}

Now the Domain is fully separated from the user interface. It can be used with both HTTP and command-line interfaces, and tested separately from them. Per the ADR pattern, the Responder becomes responsible for examining the Payload to see what kind of presentation to deliver to the client. Different Payloads result in different responses being built. Finally, the Action becomes entirely uninteresting; all of the business logic has been pushed down into the Domain, where it belongs.

So, to sum up: Command Bus is a domain layer pattern, and should be used in the Domain, not in the Action. A Command cannot return a result, but a Service can, so the entry point into the Domain is probably better as a Service that returns a Payload. This keeps the HTTP and CLI user interface logic well separated from business logic, and independently testable and reusable.



An Object Lesson in Conduct Enforcement

Full disclosure: I am acquainted with both Samantha Quinones and Matthew Trask. I have spoken at conferences with Samantha and attended her talks. Note that this post is about how codes of conduct and social expectations are selectively enforced, not about the behavior of any particular individual. If you take this post as an attack on anyone in specific then you are simultaneously "wrong" and "missing the point."

Over the weekend, a “Concerned PHP User” wrote in to the FIG to remark on the election of Samantha Quinones as a FIG secretary:

Especially in light of the recent Code Of Conduct discussions in PHP I find this selection very disheartening. Samantha was recently outed as saying some pretty offensive things to a fellow PHP conference-goer (http://matthewtrask.net/blog/My-Time-At-SunshinePHP/). She said to this first-time conference attendee: “fuck this guy” and “you need to fuck off back to the Shire”. Matthew is short, so this was a clear insult to his height, not to mention very rude. If a code of conduct was in place in PHP as it should be I can’t help but think Samantha would have at least needed a temporary ban.

Please take these concerns into consideration. In my honest opinion, the insulting of the conference goer alone (and that just within the past month!) is enough to disqualify Samantha from this position.

(You should read Matthew Trask’s full blog post, and Samantha’s reply in the comments there.)

The replies to Concerned PHP User are universally of the form “Samantha is my friend, and I know personally she didn’t mean anything by it; this happened after the conference, so the Code of Conduct didn’t apply; and besides, she apologized, so that should be the end of it.” Here is a representative sample:

Chuck Burgess:

the comments on the linked-to post indicate they have publicly reconciled their altercation without friction.

Chris Tankersley:

looking at the blog post it seems that she immediately apologized and Matthew accepted the apology, and they both agreed to start over fresh. … I think that’s the best result you can possibly get when there is friction.

To be clear, these are all good people with good intentions. But would all these defenders of Samantha be so forgiving if a man of similar community standing had said similarly derogatory things to a woman who was a first-time conference attendee?

  • Would they not see this as somehow indicative that the man had a toxic personality, was misogynist/prejudiced/bigoted/privileged, or that the behavior was a symptom of a larger structural issue of some sort?

  • Would the apology have become a starting point (instead of an ending point) leading to further demands that the man continue to prostrate himself before the mob of public opinion?

  • Would they not have cried out that “this is what keeps women from attending conferences!” and demanded further action against the man?

  • Would there not have been concerned emails sent to the man’s employer, asking if that’s really the kind of person they wanted representing their company, one who would be so rude and dismissive to a fellow community member, especially a woman?

I opine that if the event were effectively identical, but with the sexes switched, there would be a very different discussion going on now. If the roles had been reversed, an apology would not have been sufficent. If a man of Samantha’s standing had said the exact same things to a woman who was a newcomer to the conference, there’s no way the issue would be left at that. It would be taken as yet another sign of the privilege that men have in the PHP community, that they think they can treat a woman that way. He’d have been vilified, shamed, hounded, and otherwise had his life made miserable on Twitter and elsewhere. Someone would have called his employer and asked if that was really the kind of person they want representing their company.

To be clear, I am not calling for Samantha to be fired, denied a position, or otherwise have her life made miserable. I am pointing out that allowances are being made based on who the offender and offended are.

This goes back to something I’ve been saying about Social-Justice-derived Codes of Conduct in general, and the proposed Code of Conduct for PHP in specific, for a long time now: the “rules” apply differently to different people, especially depending on who is doing the enforcing. Some rule-breakers will be forgiven their transgressions, and others will be prosecuted as much as possible, merely by fact of who they are and what they represent. My shorthand for that attitude is “That’s just Joe being Joe!” – Joe’s actions, when performed by George, will result in banishment for George and forgiveness for Joe. There’s always some reason that Joe can be forgiven that will never apply to George.

So either you are in favor of all people treating others with equal respect and dignity at all times, under a Code of Conduct or otherwise, or you are in favor of some people being more equal than others and being given allowances based on who they are and what narrative they fit. If you would have punished a man for Samantha’s behavior, you should punish Samantha too; if you do not punish Samantha for her behavior this time, you should not punish anyone else in the future for any behavior resembling hers.


Finally, a side note. One commenter in the PHP-FIG thread opined: "If a code of conduct was in place, for PHP internals, then that code of conduct would have no bearing here. It is entirely a different organisation."

There is plenty of reason to believe that it would apply here, and at any time PHP community members gather together or speak with each other, regardless of location or channel.

Further, if PHP as-a-project ever adopts a Code of Conduct, that code will metastasize (through voluntary action or otherwise) across the entire PHP community. PHP user groups, projects, conferences, etc., will adopt it merely because it is “The PHP Code Of Conduct.”

So don’t believe for a moment that a PHP-project-level Code of Conduct won’t be applied to you in some fashion. It will. Prepare yourself accordingly, and speak out against it if you can.

UPDATE: Some quotes removed at the request of the quoted persons, who have since deleted their comments on the FIG thread.



You Do Not Have A Right To Contribute

(Another in a series on the proposed PHP code of conduct, itself a work in progress in at least one other place.)

Over the weekend I listened to a recent episode of the Dev Hell podcast, hosted by Chris @grmpyprogrammer Hartjes and Ed @funkatron Finkler, and guest-starring Amanda @AmbassadorAwsum Folson. (Full disclosure: I have been a guest on the podcast previously.)

The episode is #70 “Anti-Canuckite Leanings”, and in it, they discuss the proposed code of conduct starting around 26:00. You should listen to the whole discussion, which ends after about 30 minutes (and really the whole episode if you can).

There’s a lot to address in the discussion, but I’m going to concentrate on only one point. Chris Hartjes says, at about the 30:17 mark:

I think fighting against the code of conduct is a losing battle, because it will get passed. And you have a choice, you can either keep contributing to PHP, or move on and do something else. It’s as simple as that. You do not have a right to contribute to PHP, it’s a privilege. It sucks how that privilege is handed out, and it sucks how sometimes that privilege is wielded as a stick by which to beat other poeople, but at the end of the day, despite it being an open source project, it is a private project, and nobody has to take your contributions. It’s as simple as that.

He reiterates the point a few times:

(48:09) If you don’t like it, go on and contribute to another project.

(48:44) The people who complain, well they either get with the program, or they just go do something else with their time.

(51:45) If you don’t like it, just don’t participate in the project.

To be sure, Chris does not specifically say he is either for or against the code of conduct as presented in the RFC, which currently uses the language of the Contributor Covenant.

Even so, I have heard variations of this from Contributor Covenant supporters. These kinds of comments strike me as interesting in two ways.

First, “If you don’t like it, just don’t participate in the project” and its variations do not seem in the spirit of “fostering an open and welcoming community.” I see this as revealing part of the true intent of Contributor Covenant supporters: to wit, they wish to set themselves up as judges of who is to be accepted, and who is to be rejected.

Second, and more importantly, the very same argument applies in favor of the status quo; that is, not having an explicit code of conduct. Let’s take a look at the same wording, but against having a code of conduct:

If the project does not have a code of conduct, you have a choice, you can either keep contributing, or move on and do something else. It’s as simple as that. You do not have a right to contribute, it’s a privilege. At the end of the day, despite it being an open source project, it is a private project, and nobody has to take your contributions. It’s as simple as that.

So the argument is simultaneously made for not-having a code of conduct, using exactly the same wording. If you don’t like that there’s no code of conduct, “go on and contribute to another project.” After all, “you do not have a right to contribute.” You can “either get with the program, or just go do something else with your time.”

This means to me, among other things, that the burden of proof remains on those who support the Contrbutor Covenant, proof which they sorely lack, or are unwilling to put forth.

For the record, this is not an attempt to hammer on Chris, whom I count as a friend. It is an attempt only to point out one of the many flawed arguments of some who support the Contributor Covenant.

Finally, for the record, I continue to be opposed to the Contributor Covenant and anything substantially similar to or derived from it. Having no code of conduct is better than having the Contributor Covenant.



On the Proposed PHP Code of Conduct

Recently, Anthony Ferrara opened an RFC for PHP internals to adopt and enforce a code of conduct. Even leaving aside for the moment whether this is an appropriate use of the RFC system, the RFC generated a lot of discussion on the mailing list, in which I participated at great length, and for which I was hailed as abusive by at least one person in favor of the RFC (a great example of a kafkatrap).

To restate what I said on the mailing list, my position on the RFC is not merely “opposed”, but “reject entirely as unsalvageable” (though I did make some attempts at salvage in case it goes through). I continue to stand by everything I said there, and in other channels, regarding the proposed Code of Conduct.

Normally, if you had not heard about this particular discussion, I would say you were lucky, and probably the happier for it. In this case, I have to say that you should be paying close attention. The Code of Conduct as presented enables its enforcers to stand in judgment of every aspect of your public, private, professional, and political expression. I understand that’s a bold assertion; I will attempt to support it below.

The Contributor Covenant version on which the RFC is based is authored and maintained by intersectional technologist and transgender feminist Coraline Ada Ehmke. Ehmke believes that open source is a political movement:

From the onset open source has been inherently a political movement, a reaction against the socially damaging, anti-competitive motivations of governments and corporations. It began as a campaign for social liberty and digital freedom, a celebration of the success of communal efforts in the face of rampant capitalism. What is this if not a political movement?

Why Hackers Must Welcome Social Justice Advocates

Whether or not this description of open source is accurate, it is true that Ehmke thinks of open source as a political arena. As such, one must read the Contributor Covenant as a political document, with political means and political ends. Specifically, it is a tool for Social Justice.

As a tool for Social Justice, it recognizes no boundaries between project, person, and politics. This attitude is written into the Contributor Covenant with the text, “This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community.” So, when is a project participant not representing the project? The answer appears to be “never.”

That is, a project participant is always representative of the project. We can see one example of this from the “Opalgate” incident. In reference to a Twitter conversation where Opal is not the subject, Ehmke opens an Opal project issue, and then attempts (with a Social Justice mob of backers) to intimidate the project managers into removing one of the Twitter conversants from the project because of his non-project-related speech.

This is Social Justice in action. Remember, it is the author of the Contributor Covenant acting this way. To look at this incident, and simultaneously opine that the Covenant as a tool of Social Justice is somehow not political, or that it does not intend to police speech unrelated to the project, reveals that opinion as obviously incorrect. This kind of behavior is not “abuse” of the Contributor Covenant; it is the intended application of the Covenant. The Covenant is designed specifically to enable that behavior under cover of “safety” and “welcoming” and “respect”.

But “safety” and “welcoming” and “respect” are the primary goals of the Covenant, aren’t they? I assert they are the curtain behind which the true goal is veiled: power over persons who are not sufficiently supportive of Social Justice. I think is it appropriate to mention the motte and bailey doctrine here:

[The doctrine is compared] to a form of medieval castle, where there would be a field of desirable and economically productive land called a bailey, and a big ugly tower in the middle called the motte. If you were a medieval lord, you would do most of your economic activity in the bailey and get rich. If an enemy approached, you would retreat to the motte and rain down arrows on the enemy until they gave up and went away. Then you would go back to the bailey, which is the place you wanted to be all along.

So the motte-and-bailey doctrine is when you make a bold, controversial statement. Then when somebody challenges you, you claim you were just making an obvious, uncontroversial statement, so you are clearly right and they are silly for challenging you. Then when the argument is over you go back to making the bold, controversial statement.

Sentiments like “safety” and “welcoming” and “respect” are the motte of the Covenant: the defensible tower from which challengers are ridiculed. (“It’s nice! Who doesn’t want to be nice? Why do you think we should enable harassers and abusers? Why do you want to exclude women, LGBTQ, etc?”) But the real purpose of the Covenant is to enable work in the bailey: that is, to gain power over the political enemies of Social Justice, by using project membership as a form of leverage over them.

We saw that bailey-work in the Opalgate example above. As another example of attempting to use leverage, we have the following incident in the Awesome-Django project, run by Roberto Rosario. Rosario turned down a pull request, and thereafter received this demand to adopt and enforce the Contributor Convenant. (Interestingly enough, Github deleted the issue entirely, as far as I know without comment, and without notification to Rosario; the archive.is link appears to be the only evidence of the issue’s existence.)

After Rosario declined, the issue-opener ended the conversation with an attempt at intimidation: “You are a member of the Django Software Foundation and are supposed to be setting the example. I will be forwarding the content of this issue to the Chair to evaluate your continued presence in the DSF.”

Thus, the issue-opener began in the motte (“welcoming” and “respect”) but ended on the bailey (threats to leverage refusal of the Covenant into rejection from a project). Again, this is not an abuse of the Covenant. As a tool of Social Justice, that is its author’s intended purpose: to give cover for threats and intimdation against those who do not support the author’s politics.

Since threats and intimidation are the end-game, consider what else might be threatened by being insufficiently supportive of Social Justice in general, and the Contributor Covenant in specific. Any project leader, any conference organizer, any publisher, or any employer, might be approached regarding your politically-incorrect opinions as expressed on any non-project forum or subject, and be threatened and intimidated into distancing themselves from you. This leads to ejection from projects, denial or disinvitation from conferences, rejection of manuscripts, and refusal-to-hire or outright firing, based on political (not professional) concerns.

This is not the kind of behavior found in a free and open society. It is instead the behavior of a society that is totalitarian, even fascist-with-a-smiley-face. You are not allowed to disagree with the Social Justice proponents, in any capacity. You are not even allowed to “not care” – you will be made to care.

As such, I assert that the Contributor Covenant, and any other codes of conduct originating in Social Justice, are to be opposed out of hand, both in PHP, and in any other place they are suggested.

Postscript

While reading in preparation for writing this piece, I came across a lot of information that didn’t really fit, but might still be useful. Here’s a partial list of links.

Social Justice In Action

Discussions About Codes of Conduct

Alternative Codes of Conduct



Atlas: a persistence-model data mapper

Atlas is a data mapper implementation for your persistence model (not your domain model).

As such, Atlas uses the term "record" to indicate that its objects are not domain entities. Note that an Atlas record is a passive record, not an active record; it is disconnected from the database. Use Atlas records indirectly to populate your domain entities, or directly for simple data source interactions.

No migrations. No annotations. No lazy loading. No domain models. No data-type abstractions. No behaviors. No opinions. Just data source mapping.

Read more at the Github repository.


How Do You See The PHP-FIG?

Fram a Reddit discussion; please reply over there.

There are some ongoing discussions on the PHP-FIG mailing list about, among other things, how the FIG is seen by the wider PHP community.

Since an earlier discussion pointed out that perhaps the FIG, while well-known, don’t do enough “active outreach”, consider this an attempt to “reach out.”

Do you think:

  1. The FIG is a bunch of self-aggrandizing elitist jerks who couldn’t write a competent or useful “proposed standards recommendation” if their lives depended on it, and should disband entirely.

  2. The FIG, while aware that the wider PHP community is watching, writes PSRs primarily for itself, and others can adopt or ignore as they wish;

  3. The FIG has become the closest thing to a userland standards group that the PHP community has, and should accept that role;

  4. Some other opinion?

Thanks in advance for your thoughtful, considered opinion, whether positive or negative.

Again, please comment at Reddit.


How To Think Real Good

Via http://meaningness.com/metablog/how-to-think. All of the following are quotes from the article that, in general, appeal to my priors. All emphasis in original, which you should read in its entirety.


The implicit assumption is that the problem Bayesianism solves is most of rationality, and if I’m unimpressed with Bayesianism, I must advocate some other solution to that problem. I do have technical doubts about Bayesianism, but that’s not my point. Rather, I think that the problem Bayesianism addresses is a small and easy one.

- Bayesianism is a theory of probability.

- Probability is only a small part of epistemology.

- Probability is only a small part of rationality.

- Probability is a solved problem. It’s easy. The remaining controversies in the field are arcane and rarely have any practical consequence.

My answer to “If not Bayesianism, then what?” is: all of human intellectual effort.

* * *

Understanding informal reasoning is probably more important than understanding technical methods.

* * *

Many of the heuristics I collected for “How to think real good” were about how to take an unstructured, vague problem domain and get it to the point where formal methods become applicable. ... Finding a good formulation for a problem is often most of the work of solving it.

* * *

Suppose you want to understand the cause of manic depression. For every grain of sand in the universe, there is the hypothesis that this particular grain of sand is the sole cause of manic depression. Finding evidence to rule out each one individually is impractical. ... [T]here is an infinite list of logically possible causes. ... We can’t even imagine them all, much less evaluate the evidence for them. So:

Before applying any technical method, you have to already have a pretty good idea of what the form of the answer will be.

* * *

Choosing a good vocabulary, at the right level of description, is usually key to understanding.

* * *

1. A successful problem formulation has to make the distinctions that are used in the problem solution.

...

2. A successful problem formulation has to make the problem small enough that it’s easy to solve.

* * *

It’s important to understand that problem formulations are never right or wrong.

Truth does not apply to problem formulations; what matters is usefulness.

In fact,

All problem formulations are “false,” because they abstract away details of reality.

* * *

[I]f you don’t know the solution to a problem, how do you know whether your vocabulary makes the distinctions it needs? The answer is: you can’t be sure; but there are many heuristics that make finding a good formulation more likely. Here are two very general ones:

Work through several specific examples before trying to solve the general case. Looking at specific real-world details often gives an intuitive sense for what the relevant distinctions are.

Problem formulation and problem solution are mutually-recursive processes.

You need to go back and forth between trying to formulate the problem and trying to solve it.

* * *

If a problem seems too hard, the formulation is probably wrong. Drop your formal problem statement, go back to reality, and observe what is going on.

* * *

Learn from fields very different from your own. They each have ways of thinking that can be useful at surprising times. Just learning to think like an anthropologist, a psychologist, and a philosopher will beneficially stretch your mind.

...

If you only know one formal method of reasoning, you’ll try to apply it in places it doesn’t work.

* * *

- Figuring stuff out is way hard.

- There is no general method.

- Selecting and formulating problems is as important as solving them; these each require different cognitive skills.

- Problem formulation (vocabulary selection) requires careful, non-formal observation of the real world.

- A good problem formulation includes the relevant distinctions, and abstracts away irrelevant ones. This makes problem solution easy.

- Little formal tricks (like Bayesian statistics) may be useful, but any one of them is only a tiny part of what you need.

- Progress usually requires applying several methods. Learn as many different ones as possible.

- Meta-level knowledge of how a field works--which methods to apply to which sorts of problems, and how and why--is critical (and harder to get).



Configuration Values Are Dependencies, Too

As part of my consulting work, I get the opportunity to review lots of different codebases of varying modernity. One thing I’ve noticed with some otherwise-modern codebases is that they often “reach out” from inside a class to retrieve configuration values, instead of injecting those values into the class from the outside. That is, they use an equivalent of globals or service-location to read configuration, instead of using dependency injection.

Here is one generic example:

<?php
class Db
{
    // backend type, hostname, username, password, and database name
    protected $type, $host, $user, $pass, $name;

    public function __construct()
    {
        $this->type = getenv('DB_TYPE');
        $this->host = getenv('DB_HOST');
        $this->user = getenv('DB_USER');
        $this->pass = getenv('DB_PASS');
        $this->name = getenv('DB_NAME');
    }

    public function newConnection()
    {
        return new PDO(
            "{$this->type}:host={$this->host};dbname={$this->name}",
            $this->user,
            $this->pass
        );
    }
}
?>

Granted, the example follows the modern practice of keeping sensitive information as environment variables. Similar examples use $_ENV or $_SERVER keys instead of getenv(). The effect, though, is global-ish or service-locator-ish in nature: the class is reaching outside its own scope to retrieve values it needs for its own operation. Likewise, one cannot tell from the outside the class what configuration values it depends on.

Is the following any better?

<?php
class Db
{
    public function __construct()
    {
        $this->type = Config::get('db.type');
        $this->host = Config::get('db.host');
        $this->user = Config::get('db.user');
        $this->pass = Config::get('db.pass');
        $this->name = Config::get('db.name');
    }
}
?>

As far as I can tell, that’s a variation on the same theme. The generic Config object acts as a global singleton to carry configuration for every possible need; it is acting as a static service locator. While service location is inversion-of-control, it is in many ways inferior to dependency injection. As before, the class is reaching outside its own scope to retrieve values it depends on.

What if we inject the generic Config object like this?

<?php
class Db
{
    public function __construct(Config $config)
    {
        $this->type = $config->get('db.type');
        $this->host = $config->get('db.host');
        $this->user = $config->get('db.user');
        $this->pass = $config->get('db.pass');
        $this->name = $config->get('db.name');
    }
}
?>

This is a little better; at least now we can tell that the Db class needs configuration of some sort, though we still cannot tell exactly which values it needs. This is the same as injecting a service locator.

Having seen all these examples, and other similar ones, in real codebases, I conclude that configuration values should be treated as any other dependency, and injected via the constructor. I suggest this approach:

<?php
class Db
{
    public function __construct($type, $host, $user, $pass, $name)
    {
        $this->type = $type;
        $this->host = $host;
        $this->user = $user;
        $this->pass = $pass;
        $this->name = $name;
    }
}
?>

Simple, clear, obvious, and easy to test. If you use a dependency injection container of some sort, it should be trivial to have it read environment variables and pass them to the Db class at construction time. (If your DI container does not support that kind of thing, you may wish to consider using a more powerful container system.)

Alternatively, I think the following may be reasonable in some cases:

<?php
class DbConfig
{
    // backend type, hostname, username, password, and database name
    protected $type, $host, $user, $pass, $name;

    public function __construct($type, $host, $user, $pass, $name)
    {
        $this->type = $type;
        $this->host = $host;
        $this->user = $user;
        $this->pass = $pass;
        $this->name = $name;
    }

    public function getDsn()
    {
        return "{$this->type}:host={$this->host};dbname={$this->name}";
    }

    public function getUser()
    {
        return $this->user;
    }

    public function getPass()
    {
        return $this->pass;
    }
}

class Db
{
    protected $dbConfig;

    public function __construct(DbConfig $dbConfig)
    {
        $this->dbConfig = $dbConfig;
    }

    public function newConnection()
    {
        return new PDO(
            $this->dbConfig->getDsn(),
            $this->dbConfig->getUser(),
            $this->dbConfig->getPass()
        );
    }
}
?>

In that example, the DbConfig manages a set of injected configuration values so that the Db object treats its own configuration as a separate concern. However, that approach is just a little too indirect and open-to-abuse for my taste most of the time. The temptation is to start putting more and more inside the DbConfig object, and you end up with a mini-service-locator.

To sum up: Configuration values are dependencies; therefore, inject configuration values the way you would any other dependency.

UPDATE: Stephan Hochdörfer notes on Twitter: "I would probably re-phrase a bit: Configuration values should be treated like deps. Not sure if u can say that they are deps ;)." The point is well-taken, though it may be a distinction without a difference. If the class cannot operate properly without a particular value, whether that value is a scalar or an object, I think it's fair to say the class is dependent on that value.



Stop Fighting ISIS, Start Fighting Saudi Arabia

But ISIS is only a symptom of the larger disease, which is the spread of fundamentalist Wahhabist Islam from Saudi Arabia all over the world. This has become such a problem that even Germany -- which has precipitated the current "migrant" crisis in central and western Europe -- has publicly warned the Saudis against their fifth-column work. ...

Until Saudi Arabia is forcefully and directly confronted over its international financing of extremism, events like Paris and San Bernardino will continue and multiply.

Also, "The United States is not a nation-state in the sense the European countries are; it is not a country of blood relations, but of fealty to a document of western, Enlightenment principles regarding the relationship of citizen and state." Source: End the War on ISIS Now.


First Stable Aura 3.x Releases

Today we released the first round of stable Aura 3.x packages:

Since the announcement of the plans for Aura 3.x, we have made one small concession: the minimum PHP version is 5.5, instead of 5.6 as originally announced. Even so, all the 3.x packages are tested and operational on PHP 5.6, PHP 7, and HHVM.

Via the Aura blog at http://auraphp.com/blog/2015/12/01/aura-3-stable-releases/.