Injecting controller actions in Laravel views

Disclaimer: Depending on the kind of logic you need, it’s also possible to use View Composers to achieve a similar result.

I’m using Laravel in this new project I’m working on. Some other PHP frameworks have a feature to use controllers as services. Symfony, for instance, has something like that. The project team thought Laravel, as Symfony-based, would have something like that. Well, if it has, it’s not clear in the docs.

Another team member ended up with a solution I never thought before:

 @inject('someController', 'App\Http\Controllers\SomeController')
 {!! $someController->index() !!}

Now, we’re using Blade’s @inject directive to call controller actions from inside views. That’s useful for reusing actions as widgets, for example.

If you find that interesting and want to use in your application, remember two things:

  1. Since you’re calling the action method directly, you have to pass all the required params. If it expects a request instance, you can do this: $someController->index(request()).
  2. Probably the method returns a view that contains HTML code. So wrap the call within {!! and !!}. Using the {{ }} regular tag will cause the code to be escaped.

Multiple Domain plugin for WordPress

For a few projects in the past, I had to find a way to make WordPress work with more than one domain. There are a couple plugins to do that, but they are outdated and/or don’t work well. So, I wrote this plugin.

Check this out:

Multiple Domain allows you having more than one domain in a single WordPress installation. This plugin doesn’t support more than one theme or advanced customizations for each domain. It’s only intended to enable constant navigation under many domains. For a more complex setup, there is WordPress Multisite (MU).

When there is more than one domain set in your host, all links and resources will point to the default domain. This is the default WordPress behavior. With Multiple Domain installed and properly configured, it’ll update all link on the fly. This way, the user navigation will be end-to-end under the same domain.

You can also set an optional base URL. If you want only a set of URL’s available under a given domain, you can use this restriction.

Photo credit: Roya Ann Miller

Passing Node args to Mocha tests

This is a really quick tip. I was looking around on the internet for a way to pass Node arguments when calling Mocha binary. And I couldn’t find anything useful. Then I tried the following and it worked:

$ test node --expose-gc ./node_modules/.bin/mocha [...]

The --expose-gc argument is just an example. You can pass any argument accepted by Node program.

In my specific case, I was trying to load dotenv config. In the end, the project’s MakeFile looked like:

    @NODE_ENV=test node -r dotenv/config ./node_modules/.bin/mocha \
        --require should \
        --reporter spec \
        --harmony \
        --bail \

.PHONY: test

Photo credit: Matt Benson

Mixing HTTP and WebSocket routes in a Koa-based application

I’ve started to use the koa-websocket package. And it took me some time to figure out how to mix HTTP and WebSocket routes in a single Koa-based application. I’m not sure if this solution is obvious, but I’m sharing it anyway.

First of all, we’ll need two separate routers for regular HTTP and WebSocket routes:

// Creating a Koa app instance.
const app = require('koa')();
// "Websockifying" the application.
const socket = (require('koa-websocket'))(app);
// Loading router package
const router = require('koa-router');

// Here they are, our 2 routers
const http = router();
const ws = router();

Then, we can write our routes, plugging them to the specific router:

http.get('/', function *(next) {
    this.status = 200;
    this.body = 'Hello!';

ws.get('/socket', function *(next) {
    this.websocket.on('message', function (message) {

Finally, let’s make the app use the routers we created:


Notice that the second router was added to instead of app directly.

And… That’s it.

Photo credit: Aron Van de Pol

Propel ModelCriteria : leftJoin + useQuery

When using leftJoin and useQuery from a ModelCriteria (Query class), you can set the join type, this way:

// ...
->useFooQuery(null, \Criteria::LEFT_JOIN)
// ...
// ...


Propel + Symfony2 : Debugando queries em comandos

Quando no ambiente de desenvolvimento, em um projeto baseado no Symfony2, usar o webprofiler na interface web (a partir da barra que fica no rodapé das páginas) é uma mão na roda em várias situações. Mas no console geralmente não temos essa facilidade tão a mão, porém não é impossível acessá-la. Especificamente para as queries executadas através do Propel, é possível usar o seguinte trecho para fins de debug:

$profiler = $this->getContainer()->get('profiler');
$db = $profiler->get('propel');
$db->collect(new \Symfony\Component\HttpFoundation\Request(), new \Symfony\Component\HttpFoundation\Response()); // Stubs, não são usados pelo profiler

Você pode dar uma olhada na classe Symfony\Bridge\Propel1\DataCollector\PropelDataCollector e conferir os métodos disponíveis.

Outros profilers podem ser acessados através do container, mas como a requisição (request) e a resposta (response) não estão disponíveis no console, pode ser que nem todos funcionem como esperado.

Testando comandos do Symfony que usam serviços da aplicação

Se você tem um comando no Symfony2 que usa serviços da aplicação, como um ORM por exemplo, e seguir o modelo que a documentação do framework fornece para escrever testes unitários, poderá ver erros com os a seguir:

Fatal error: Call to undefined method Symfony\Component\Console\Application::getKernel() in [...]/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Command/ContainerAwareCommand.php on line [...]

ao acessar o kernel da aplicação, a partir do comando, ou:

Fatal error: Call to a member function getParameter() on a non-object in [...]

ao tentar acessar algum método do container.

O primeiro caso, acontece quando você usa a classe Symfony\Component\Console\Application ao invés de Symfony\Bundle\FrameworkBundle\Console\Application. Verifique os uses da sua classe de testes e ajuste se for necessário.

A segunda exceção é lançada quando você está usando a classe Application correta, mas usando um kernel inválido na sua instanciação. Talvez exista outro modo de fazer isso, mas para mim funcionou extender a classe Symfony\Bundle\FrameworkBundle\Test\WebTestCase no lugar de \PHPUnit_Framework_TestCase e construir a aplicação da seguinte forma:

$application = new Application(self::createClient()->getKernel());