Paul M. Jones

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

Camille Paglia: On Trump, Democrats, Transgenderism, and Islamist Terror

The cold biological truth is that sex changes are impossible. Every single cell of the human body remains coded with one's birth gender for life. Intersex ambiguities can occur, but they are developmental anomalies that represent a tiny proportion of all human births.In a democracy, everyone, no matter how nonconformist or eccentric, should be free from harassment and abuse. But at the same time, no one deserves special rights, protections, or privileges on the basis of their eccentricity. The categories "trans-man" and "trans-woman" are highly accurate and deserving of respect. But like Germaine Greer and Sheila Jeffreys, I reject state-sponsored coercion to call someone a "woman" or a "man" simply on the basis of his or her subjective feeling about it. We may well take the path of good will and defer to courtesy on such occasions, but it is our choice alone.

A wide-ranging interview. Source: Camille Paglia: On Trump, Democrats, Transgenderism, and Islamist Terror | The Weekly Standard


No, You’re Not More Likely to Be Killed by a Right-Wing Extremist than an Islamic Terrorist

The fact that the two deadliest attacks upon the U.K. in recent memory were at the hands of Islamic terrorists is not simply pub trivia. I mention it because when these apologists for Islam get bored of claiming that jihadists are incessantly and inexplicably lying about their religious motivations, they invariably engage in the crass exercise of throwing around skewed data in a desperate attempt to deemphasize the danger posed by Islamic terror. this is not due to some well-meaning concern for people worrying unnecessarily, or to ensure that counter terrorism strategy is accurately focused upon the most serious threat, it seems rather to be a tactical attempt to prioritize the protection of odious 7th century folklore over the welfare of real human beings.

In the not uncommon event of an Islamic lunatic slaughtering a crowd of innocent people, Americentric articles and tweets lying about the likelihood of this happening to you, instantaneously begin to surface, like gunk from the ocean floor after a depth charge detonation.

Source: No, You’re Not More Likely to Be Killed by a Right-Wing Extremist than an Islamic Terrorist – Areo Magazine


How Oxford and Peter Singer drove me from atheism to Jesus

Christianity, it turned out, looked nothing like the caricature I once held. I found the story of Jacob wrestling with God especially compelling: God wants anything but the unthinking faith I had once assumed characterized Christianity. God wants us to wrestle with Him; to struggle through doubt and faith, sorrow and hope. Moreover, God wants broken people, not self-righteous ones. And salvation is not about us earning our way to some place in the clouds through good works. On the contrary; there is nothing we can do to reconcile ourselves to God. As a historian, this made profound sense to me. I was too aware of the cycles of poverty, violence and injustice in human history to think that some utopian design of our own, scientific or otherwise, might save us.

Source: How Oxford and Peter Singer drove me from atheism to Jesus - The Veritas Forum - The Veritas Forum


Can a scientist believe in the resurrection?

To explain how a scientist can be a Christian is actually quite simple. Science cannot and does not disprove the resurrection. Natural science describes the normal reproducible working of the world of nature. Indeed, the key meaning of “nature”, as Boyle emphasized, is “the normal course of events.” Miracles like the resurrection are inherently abnormal. It does not take modern science to tell us that humans don’t rise from the dead. People knew that perfectly well in the first century; just as they knew that the blind from birth don’t as adults regain their sight, or water doesn’t instantly turn into wine.

Source: Can a scientist believe in the resurrection? Three hypotheses. - The Veritas Forum - The Veritas Forum


Controllers and Domain Exceptions

A few months ago I had a great email conversation with a correspondent about how to handle business logic exceptions in his controller code. His message follows, lightly edited for brevity and clarity:

I think controller has single responsibility - to mediate communication between caller's context and actual business logic services. (I believe business logic services should be unaware of caller's context, be it HTTP request or CLI.)

Given that services should be unaware of who called them, they should not throw HTTP-specific exceptions. So instead of throwing a Symfony HttpNotFound Exception, the service would throw ObjectNotFound (which is HTTP agnostic) in cases where DB record could not be found.

Yet at the same time the logic that converts exceptions to HTTP responses expects HTTP-specific Symfony exceptions. This means that the exception thrown by service needs to be transformed into Symfony exception.

One of solutions I see to this is that the controller could take that responsibility. It would catch domain exceptions thrown by service and wrap them into appropriate HTTP exceptions.

class FooController
{
    public function fooAction()
    {
        try {
            $this->service->doSomething('foo');
        } catch (ObjectNotFound $e) {
            throw new NotFoundHttpException('Not Found', $e);
        } catch (InvalidDataException $e) {
            throw new BadRequestHttpException('Invalid value', $e);
        } // ...
    }
}

The downside I see with this approach is that if I have many controllers I will have code duplication. This also could lead to big amount of catch blocks, because of many possible exceptions that could be thrown.

Another approach would be to not have try/catch blocks in controller and let the exceptions thrown by service bubble up the stack, leaving the exception handling to exception handler. This approach would solve the code duplication issue and many try/catch block issue. However, because the response builder only accepts Symfony exceptions, they would need to be mapped somewhere.

It also feels to me that this way the controller is made cleaner, but part of controllers responsibility is delegated to something else, thus breaking encapsulation. I feel like it's controllers job to decide what status code should be retuned in each case, yet at the same time, cases usually are the same.

I truly hope you will be able to share your thoughts on this and the ways you would tackle this.

If you find yourself in this situation, the first question to ask yourself is, “Why am I handling domain exceptions in my user interface code?” (Remember: Model-View-Controller and Action-Domain-Responder are user interface patterns; in this case, the user interface is composed of an HTTP request and response.) Domain exceptions should be handled by the domain logic in a domain-appropriate fashion.

My correspondent’s first intuition (using domain-level exceptions, not HTTP-specific ones) has the right spirit. However, instead of having the domain service throw exceptions for the user interface controller to catch and handle, I suggest that the service return a Domain Payload with domain-specific status reporting. Then the user interface can inspect the Domain Payload to determine how to respond. I expand on that approach in this post.

By way of example, instead of this in your controller …

class FooController
{
    public function fooAction()
    {
        try {
            $this->service->doSomething('foo');
        } catch (ObjectNotFound $e) {
            throw new NotFoundHttpException('Not Found', $e);
        } catch (InvalidDataException $e) {
            throw new BadRequestHttpException('Invalid value', $e);
        } // ...
    }
}

… try something more like this:

class FooController
{
    public function fooAction()
    {
        $payload = $this->service->doSomething('foo');
        switch ($payload->getStatus()) {
            case $payload::OBJECT_NOT_FOUND:
                throw new NotFoundHttpException($payload->getMessage());
            case $payload::INVALID_DATA:
                throw new BadRequestHttpException($payload->getMessage());
            // ...
        }
    }
}

(I am not a fan of using exceptions to manage flow control; I’d rather return a new Response object. However, I am trying to stick as closely to the original example as possible so that the differences are more easily examined.)

The idea here is to keep domain logic in the domain layer (in this case, a service). The service should validate the input, and if it fails, return a “not-valid” payload. The service should catch all exceptions, and return a payload that describes the kind of error that occurred. You can then refine your controller to examine the Domain Payload and handle it however you want.

Using a Domain Payload in this way is not a huge leap. Essentially you move from a try/catch block and exception classes, to a switch/case block and status constants. What’s important is that you are now handling domain-level exceptions in the domain and not in the user interface layer. You are also encapsulating the status information reported by the domain, so that you can pass the Domain Payload object around for something other than the controller to inspect and handle.

Encapsulation via Domain Payload opens the path to a more significant refactoring that will help reduce repetition of response-building logic across many controller actions. That next refactoring is to separate out the response-building work to a Responder, and use the Responder in the controller action to return a response. You can then pass the Domain Payload to the Responder for it to handle.

class FooController
{
    public function fooAction()
    {
        $payload = $this->service->doSomething('foo');
        return $this->responder->respond($payload);
    }
}

class FooResponder
{
    public function respond($payload)
    {
        switch ($payload->getStatus()) {
            case $payload::OBJECT_NOT_FOUND:
                throw new NotFoundHttpException('Not Found', $e);
            case $payload::INVALID_DATA:
                throw new BadRequestHttpException('Invalid value', $e);
            // ...
        }
    }
}

Once you do that, you’ll realize the majority of your response-building logic can go into a common or base Responder. Custom cases can then be be handled by controller- or format-specific Responders.

And then you’ll realize all your Action logic is all pretty much the same: collect input from the Request, pass that input to a Domain-layer service to get back a Domain Payload result, and pass that result to a Responder to get back a Response. At that point you’ll be able to get rid of controllers entirely, in favor of a single standardized action handler.


"Action Injection" As A Code Smell

Circumstance has conspired to put Action Injection discussions in front of me multiple times in the past few days. Having seen the approach several times before, I have come to think that if Action Injection is the answer, you might be asking the wrong question. I find it to be a code smell, one that indicates the system needs refactoring or reorganizing.

Action Injection …

As far as I can tell, the term “Action Injection” originates with Alex Meyer-Gleaves in a 2010 article on ASP.NET MVC development. He summarizes Action Injection in this way:

Your [controller class] constructor is provided the dependencies [by the DI container] that are shared by all actions in your controller, and each individual action [method] can request any additional dependencies that it needs.

To expand on that, let’s say you have a controller class with several action methods in it. You realize after a while that the different action methods have slightly different dependencies. For example, some of the methods need a logger, while others need a template system, or access to the router. But you don’t want to pollute the controller class constructor with these method-specific dependencies, since those dependencies will be used only if that particular action method gets invoked.

With Action Injection, when you pull the controller from your dependency injection container and call a particular action method, the DI container will automatically pass the right dependencies for the method call arguments. Voila: now you can define all the common dependencies as parameters on the controller constructor, and all the action-specific dependencies as parameters on the method definition.

You can see a PHP-specific description of the problem, with Action Injection as the solution, in this Symfony pull request:

https://github.com/symfony/symfony/pull/21771

You can also hear about it in this presentation from Beau Simensen, from around 32:21 to 34:31:

https://www.youtube.com/watch?v=JyrgwMagwEM&feature=youtu.be&t=1941

The Yii and Laravel containers appear to support this behavior as well, using the term “method injection.” (I think that’s a misnomer; the term appears overloaded at best, as sometimes it may mean “methods called by the DI container at object-creation time” instead of “resolving method arguments at call-time”.) Perhaps other DI containers support Action Injection as well.

… As A Code Smell

The explicit reason for using Action Injection is “to reduce dependencies or overhead” when constructing an object. You don’t want to have to pass in a dozen dependencies, when only three are used in every method, and the others are used only in specific methods.

But the fact that your controller has so many dependencies, used only in some cases and not in others, should be an indicator that the class is doing too much. Indeed, it’s doing so much that you cannot call its action methods directly; you have to use the dependency injection container not only to build the controller object but also to invoke its action methods.

Reorganizing To Avoid Action Injection

What approaches exist to help you avoid the Action Injection code smell? I assert that the better solution is to change how you organize your controller structures.

Instead of thinking in terms of “a controller class with action methods,” think in terms of “a controller namespace with action classes.” Actions are the targets for your routes anyway, not controller classes per se, so it makes sense to upgrade actions to “first-class” elements of the system. (Think of them as single-action controllers, if you like.)

Thus, instead of …

<?php
namespace App;

class BlogController {
    public function browse() { ... }
    public function read() { ... }
    public function edit() { ... }
    public function add() { ... }
    public function delete() { ... }
}

… reorganize to:

<?php
namespace App\BlogController;

class Browse { ... }
class Read { ... }
class Edit { ... }
class Add { ... }
class Delete { ... }

Then the DI container can use plain old constructor injection to create the Action object, with all of its particular dependencies. To invoke the Action, call a well-known method with the user input from the route or request. (I like __invoke() but others may prefer exec() or something similar.)

In fact, I realized only after watching the Simensen clip a second time that his example is a single-action controller in everything but name. His example code was this …

<?php
class Home {
    /**
     * @Route("/myaction", name="my_action")
     */
    public function myAction(
        Request $request,
        Router $router,
        Twig $twig
    ) {
        if (!$request->isMethod('GET')) {
            return new RedirectResponse(
                $router->generateUrl('my_action'),
                301
            );
        }

        return new Response(
            $twig->render('mytemplate.html.twig')
        );
    }
}

… but the controller action method parameters might just as well be Action class constructor parameters:

<?php
namespace Home;

class MyAction {

    public function __construct(
        Request $request,
        Router $router,
        Twig $twig
    ) {
        $this->request = $request;
        $this->router = $router;
        $this->twig = $twig;
    }

    /**
     * @Route("/myaction", name="my_action")
     */
    public function __invoke() {
        if (!$this->request->isMethod('GET')) {
            return new RedirectResponse(
                $this->router->generateUrl('my_action'),
                301
            );
        }

        return new Response(
            $this->twig->render('mytemplate.html.twig')
        );
    }
}

(UPDATE: That example code looks like it originates from Kevin Dunglas and his DunglasActionBundle -- which is itself a single-action controller implementation for Symfony.)

Action Domain Responder

For more on this organizational structure, please read my Action Domain Responder offering. ADR is a refinement of MVC that is tuned specifically to server-side request/response over-the-network interactions.

But you need not go full ADR to avoid Action Injection. Just using single-action controllers will do the trick. Then you can have well-factored single-responsibility controller classes that do not require a DI container in order to call their action methods, and Action Injection becomes a thing of the past.


Toward A Better Separation of Session Behaviors in PHP

Andrew Shell asks, What is the best way to handle sessions with ADR? (The problem is that the built-in PHP session extension combines the concerns of reading input, managing storage, and sending output; the solution is a domain-layer session-data manager.)

I’ve reached a point with a couple of my Radar projects where I need to add a login and set permissions. I’m trying to figure out the best way to handle this, especially with PSR-7 and ADR. ...

[In Action-Domain-Responder] it’s ok to read the session cookie in an Input class, and it’s ok to write the cookie in a Responder class, but pretty much everything else should be in the Domain layer. ...

[In the Domain layer,] Cadre.DomainSession takes a session id (or generates one) and loads session data from storage. It’s smart enough to handle regenerating session ids and cleaning up expired sessions.

Read the whole article at FutureProof PHP for examples and links!

UPDATE: Reddit discussion.


"A False Sense of Simplicity"

These year-old posts from Piotr Solnica are about Ruby On Rails ...

... but the experiences related therein should be valuable to anyone using or building a full-stack PHP framework. (I can imagine it applying to CMSes as well.)

Does this story from Piotr remind you of any framework-based project you've worked on in PHP?

Once, I joined an existing project. It was a huuuuge app which was running an on-line shopping community website. Complicated sales model, complicated promotions, complicated product setups, coupons, user groups, messages - it had it all. I joined them to help ship a few new features. One of my early tasks was to ... add a link to something on some page. It took me few days to add this stupid link. Why? The app was a big ball of complex domain logic scattered across multiple layers with view templates so complicated, it wasn’t even simple to find the right template where the link was supposed to be added. Since I needed some data in order to create that link, it wasn’t obvious how I should get it. There was a lack of internal application APIs and relying on ActiveRecord exclusively made it extremely difficult.

I've consulted on projects like that more than once. Indeed, the posts might well have been subtitled "The Perils of Convenience-Oriented Development":

People are attracted by Rails because it gives you a false sense of simplicity, whereas what really happens is that complexity is being hidden by convenient interfaces.

Read both of the posts, and see if you can relate. They just reinforce to me that this is what to expect when you embed your domain logic in your user interface logic.

Remember: with server-side web-based applications, the user interface is the HTTP request and response. Any code that reads from the request, or that writes to the response, is part of the user interface. Putting your domain logic in the user interface is convenient to start with, but as soon as things become even a little bit complex, that "convenience" becomes a burden.


How to take on institutionalized Progressives and win

  1. Don’t back down. Ever.
  2. Don’t apologize for liking what you like. Especially when it runs counter to the SJW agenda.
  3. You are going to get called names. If you take a stand, even if it’s just a call not to be hasty, you will be called names. Ignore them.
  4. Allies are important. Gamers rallied around each other, regardless of skin color, confused sexual orientation, disability, sex, or just about any other metric the Progressives use to divide society into smaller groups. That doesn’t mean you need to accept their agendas and goals outside of the immediate problem, but if they are shooting at enemy, let them.
  5. Winning takes effort. Winning takes time. You’re going to lose ground now and then. See #1.
  6. The social pressure to give in and conform will be intense. See #1.
  7. A lot of battles can be won by just showing up and taking the field. The enemy has power, true, but not all that you will face. Sometimes just shedding a little light will have them running.
  8. Memes. Rhetorical attacks with memes are powerful. It dispirits the enemy. It raises the morale of your side.
  9. Last on my list, but there are others lessons, have fun. A song in the heart and a smile on the lips will confound the enemy many times over.

Source: Gamergate as an effective template for defense against SJWs - Men Of The West


Atlas ORM 1.2.0 Released

The 1.2.0 release adds the ability to define WHERE conditions on relationships. (The 1.1.0 release added functionality to ignore foreign key string case when wiring up objects in memory, and 1.0.0 was released pretty quietly a couple of weeks ago.)

Try it out today, because you like keeping your persistence layer separate from your domain layer.

Now, read on for some history, if you care about that kind of thing.


Many years ago, we on the Solar project developed Solar_Sql_Model, an Active Record type of ORM. Overall I liked it well enough, though (as with anything) it had its strengths and weaknesses.

Since then, after extracting the Solar components to Aura libraries, I’ve mostly lived without ORMs. The majority of my legacy consulting work has not made use of them; where a legacy project did have an ORM of some sort, it was a custom in-house piece of work.

However, about three years ago, I hired on with a startup to build out their backend from scratch. At the time, I wanted to do “real” Domain-Driven Design, with entities and aggregates and value objects and everything else. That meant keeping the domain system separate from the persistence system, and that in turn meant Active Record was not an option. Doctrine, a domain model data mapper, was the next logical choice, but on review it was not to my liking. (The annotations, among other things about Doctrine, just rubbed me the wrong way.)

So instead of an Active Record implementation, or Doctrine, I figured that it would be enough to use a Table Data Gateway on top of Aura.Sql and Aura.SqlQuery to retrieve rows, then map the rows over to domain objects. This was fine, for as far as it went, but the problem was “relationships.” Oh dear Codd, the relationships.

Selecting one or many objects from a single table was no big deal, but doing multiple selections from multiple tables and building up the selection statements for those relationships was a tedious, tiresome, and time-consuming burden. (Wiring them up in memory once they’d been selected was not too bad, given Aura.Marshal, but it was still more effort than I’d’ve rather been expending.)

So it all “worked,” but it was just not satisfying at all. The DDD portions, for their part, worked out great, as did the separation of the domain layer from the persistence layer, so I was pretty sure I was on something like the right track.

Then I read this article from Mehdi Khalili. It’s fantastic and you should read the whole thing. In summary, Khalili points out that it is perfectly reasonable to use a persistence model in addition to a domain model. That is, you do not necessarily have to map directly from the database to domain objects; you can map from the database to persistence objects for the data, and then later compose or map the persistence model into the domain model for behaviors.

This was a revelation to me, something that I’d never considered, or even heard of before. It alleviates wide swaths of DDD-related burdens.

As a result of my relationship-related burdens at the startup, and after reading the Khalili article, I put together Atlas, a mapper for your persistence model. Like everything else I’ve been doing for the past several years, Atlas is built in discrete layers:

  • PDO at the very bottom;
  • Aura.Sql around that, to provide convenience methods for binding and fetching;
  • Aura.SqlQuery in parallel, to support query building;
  • all of those composed into a table data gateway system to emit Row objects from tables;
  • and finally a mapper system on top of that to emit Record objects composed of table Rows and their relationships

As such, each Record object is composed of a Row (from the “main” table) and its Related objects (themselves Records, each of which is composed of a Row and Relateds, and so on).

Atlas uses the term “Record” to indicate that the object is not a domain entity or aggregate. You can use Records directly for straightforward CRUD/BREAD operations, or you can map them over to your domain objects.

Fetching deep relationship structures is no big deal; see this article from Andrew Shell using 25 tables in different complex relationships. (Andrew’s project also shows how to keep the persistence and domain layers separate, and incorporates a debug bar implementation for Atlas.)

So, if you want a data mapper implementation that models your persistence layer, and the relationships therein, Atlas is just the thing for you. Try it out today!