Categorias
Tropeçando

Tropeçando 106

5 Constant Lists That Give Context to your Integers and Strings

Enum i a great feature of modern software development. Here you will find five lists that lives in Enums (or Enum-like) that add lots of context for your code. It will look better and cleaner.

Validate all the things: improve your security with input validation!

If there's one habit that can make software more secure, it's probably input validation. Here's how to apply OWASP Proactive Control C5 (Validate All Inputs) to your code.

TypeScript Utility Types: The 6 Most Useful

Write better typescript code by using typescript utility types. Record, Partial, Required, Omit, Pick, Exclude utilities.

Query parameter data types and performance

Recently, I could help solve a “mysterious” performance problem for a customer. The problem turned out to be a badly chosen query parameter type, which led to poor query performance. After working on this customer’s case, I realized that the meaning of the data type of a query parameter is not universally understood, which is why I decided to write this article.

Terraform Best Practices

Building Serverless Applications That Scale The Perfect Amount

Great reasoning about how to think about the architecture that scale on Serverless, thinking about the load and costs.

Run a PHP application on AWS Fargate

An example for a pipeline to configure and deploy a PHP application on AWS Fargate.

6 Signs Your Daily Standups Aren’t Working

Architecture Decision Records help you, your team, and future teams

Decisions are made everyday and often the number of daily decisions make us forget older ones. Keeping a record of the decisions is a great tool to revisit what was done and also be more confident that a change can be made, when a previous statement become obsolete somehow. ADRs are a great tool for a mature software.

Waiting for PostgreSQL 15 – Add support for MERGE SQL command

MERGE SQL commands is able to perform INSERT/UPDATE/DELETE based on a base query and some conditions. This is very useful for some business logic that can be applied directly on the database data.

Categorias
Tropeçando

Tropeçando 105

CQRS and Event Sourcing implementation in PHP

A walk-through of using CQRS along with Event Sourcering using PHP.

Is my autovacuum configured properly?

Some tips to identify if you need to tune your autovacuum configurations. A proper house cleaning can improve your database health and performance.

Learn how to migrate to the PHP framework Symfony

SensioLabs and Smile released a joint white paper “PHP framework migration: from legacy to Symfony” explaining how to migrate to modern PHP frameworks like Symfony. Find a selection of the key information in this infographic design by SensioLabs.

trufflehog

Find leaked credentials. Search on your repos, source-code, etc.

Why we don’t use a staging environment

Squeaky deploys their code directly from laptops to production environments. The blog posts details their strategies, such as a good suite of tests, clear branch strategy and use of feature flags.

Scaling containers on AWS in 2022

Benchmarking for different types of workloads and scales capabilities on AWS services in 2022: lambda, EKS, ECS, Fargate...

Building well-architected serverless applications: Introduction

Multi-part series addressing each of the questions within the Serverless Lens of the Well-Architected Tool.

Comparing Workflows

Comparision of different types of git flows: centralized, feature branch, gitflow and fork flow. Simple comparision, but easy to get the sense of their use cases.

Construct Hub

Find libraries for AWS Cloud Development Kit (AWS CDK), which generates AWS CloudFormation templates, CDK for Terraform (CDKtf), which generates HashiCorp Terraform configuration files, and CDK for Kubernetes (CDK8s), which generates Kubernetes manifests.

Too much magic?

A good thinking about the "magic" under some awesomeness that are provided by frameworks or libraries. Although they are good for quicker development, there is good to think a little bit more about how and when use it when we have a software that we aim to last longer and get to the phase of greater maintainability.

Categorias
Tropeçando

Tropeçando 20 – Republish

Activate Remote Desktop REMOTELY!!! | commandlinefu.com

PHP é à quinta-feira – 50 dicas sobre desempenho e segurança | Peopleware

Howto access ext3 partition from Windows | Ubuntu Geek

This tutorial will allow you to access your ext3 partition under Windows, using Sun VirtualBox and Ubuntu. The tutorial is pretty long due to the images, but they explain things easier sometimes (they are not just meaningless screenshots) (forgive me for your scroll button 😛 )

Upload Pie - The Simple Image Sharing Tool

Sharing files with expiration dates

Mantis Bug Tracker

Gerenciamento de erros

TIOBE Software: Tiobe Index

Index of languages being used around the world.

Busca de CEP em PHP, Ajax, PHP, ASP, Java, Python, Flash, XML, C#, Ruby

Color Fading Menu with jQuery | CSS-Tricks

Increase your internet speed with Namebench | Ubuntu Geek

Guia de referência de comando em PT-BR | Ubuntu Dicas

Uma lista com os comandos mais usados no linux em português brasileiro. É possível salvar os comandos em algum imagem para que fique como um papel de parede.

Blog do Márcio d’Ávila » Fraude Surpreendo - Proteja seus dados pessoais

RootSudo - Ubuntu Brasil

Ripando e Gerando DVDs no Linux de forma simples « jmmwrite – simples e direto

Categorias
Tropeçando

Tropeçando 16 – Republish

FTP mini-HOWTO (Linux)

Eficiência e segurança com SQL parametrizado

O uso de comandos SQL, na maioria das linguagens de programação e gerenciadores de bancos de dados que suportam esta linguagem de manipulação de dados, pode ser parametrizado com variáveis de ligação (bind variables). Este recurso que, para um programador desavisado e inexperiente, pode parecer uma burocracia desnecessária, na verdade é um mecanismo muito importante para trazer segurança e eficiência ao uso de SQL em programas. Veja porque e como.

PHP: SQL Injection

Documentation for preventing SQL injection in PHP projects. Many web developers are unaware of how SQL queries can be handled and assume that an SQL query is a reliable command. It means that SQL queries are able to bypass access controls undetected, therefore bypassing standard authentication and authorization checks, and sometimes SQL queries can allow command access at the server operating system level.

PHP: Relatando Erros - Manual

Senhas armazenadas com segurança

Como Criar um Website :: Avi Alkalay

As 5 distribuições que mudaram o Linux

Segundo a chamada deste artigo da edição internacional da Linux Magazine, a história do Linux pode ser medida com base nas versões deste kernel, mas também pode ser medida pelas suas principais distribuições.

MySQL: Oracle assume um compromisso: GPL, documentado, sem contrato de suporte obrigatório, etc.

Scrum - Wikipédia, a enciclopédia livre

O Scrum é uma metodologia ágil para Gerenciamento de Projetos.

CentOS: Instalando mod_security

Spam: CGI.br determina bloqueio da porta 25 (smtp) a partir de janeiro

vivaotux: Afinando seu violão usando o bash - geek d+

[Dicas-L] Lista de servidores DNS abertos e rápidos

Categorias
Tropeçando

Tropeçando 8 – Republish

Evitando frustrações com sessões no PHP | Igor Escobar // Blog

PHP web applications can complement state in your applications very easily. Why is an illusion of state maintained by transporting one page and other information between one page and another losing it along the way. you've already lost potential productivity due to bizarre bugs or even security breaches because of these beauties. Here are four tips to save you time and secure your site. (in portuguese)

Javascript: Onunload VS Onbeforeunload | Igor Escobar // Blog

Fico pensando em um caso mais familiar possível para ilustrar a utilidade das duas funções e a melhor que me vem a cabeça é o Gmail. Já pensou em fazer algo parecido com o Gmail? Quando o usuário fechar a janela e alguma requisição estiver em processamento ele da um aviso sobre ela para evitar perda sem necessídade. Muita gente pensa que o evento utilizado para fazer tal proeza é o evento “onunload” mas não é. Existe uma pequena diferença entre os 2 eventos.

8 Regular Expressions You Should Know - Nettuts+

8 expressões regulares que você deve conhecer

The Web Application Security Consortium / The Web Security Glossary

The Web Security Glossary is an alphabetical index of terms and terminology relating to web application security. The purpose of the Glossary is to clarify the language used within the community.

The Novel 100: The 100 Greatest Novels of All Time

pdftk - the pdf toolkit

Dividindo dados em colunas - Mauro Pichiliani - SQL Server

Olá, pessoal. Hoje veremos uma solução que utilizei para manipular um conjunto de linhas e colunas no SQL Server com o objetivo de separá-las em dois conjuntos de colunas e facilitar a visualização dos dados, uma operação que geralmente não é fácil de ser realizada nos bancos de dados relacionais. Apesar de utilizar o SQL Server como exemplo, a técnica apresentada nesta coluna pode ser adaptada para outros bancos de dados que suportem a linguagem SQL sem problemas.

yfrog - Share your images/videos on Twitter!

Media Converter - the fastest free online audio and video converter

Vacation relaxation

Categorias
Tropeçando

Tropeçando 2 – Republish

dBpoweramp: CD Ripper & Audio Converter. Secure ripping to mp3, FLAC, m4a, Apple Lossless & WMA

CD extractor and multi converter from different audio and video codecs. Lots of advanced options for different formats.

A última de bluetooth - rede entre dois GNU/Linux

No trabalho você tem um pc ligado a internet via wifi, ethernet, ou similares. Você leva seu notebook que gostaria que estivesse conectado também, como fica? Você está no aeroporto com mais uma pessoa, os dois de notebook, só um modem 3G, como fica? E se vocês tiverem só um login da Vex, prestadora de acesso wifi, como fica? Você faz uma rede bluetooth entre os dois e compartilha a conexão, ora. (com exceção do primeiro, todos os comandos abaixo são como root)

Paje Online: Como Converter Vídeos no Linux?

Converter arquivos de vídeos e som no Linux, abrangendo os mais variados formatos e codecs, pode ser uma tarefa razoavelmente simples, bastando conhecer o programa certo. Nesta dica vamos apresentar o programa ffmpeg.

Ubuntu Basic Commands

An extensive list of essential Linux commands that every Ubuntu user will find helpful in their Linux journey.

Instructables - Make, How To, and DIY

Aprenda a fazer tudo

PHP é à quinta-feira - Gerar uma password | Peopleware

Um conjunto de funções que os ajudarão a gerar uma password (ou qualquer outra string de caracteres aleatórios).

Color Hunter

crie e encontre paleta de cores a partir de imagens

Sua Língua » Arquivo » Não compre o novo VOLP! — 1ª parte

Blank/erase a DVD-RW | commandlinefu.com

Apagando um DVD-RW na linha de comando

Se eu soubesse que web 2.0 era isso… » CrisDias weblog

nth-child | Boas práticas de Desenvolvimento com Padrões Web

9 Interesting Facts To Know About a Website | Tools

Os top cinco erros não técnicos cometidos por desenvolvedores | Pacote201.com.br

Blog do Márcio d’Ávila » Cuidado - A fraude evoluiu

Dicas para evitar fraudes da internet.

Categorias
PHP

PHP 8.1: more on new in initializers

I could not agree more with Brent when he says concerning the "new in initializers"[1] feature:

PHP 8.1 adds a feature that might seem like a small detail, but one that I think will have a significant day-by-day impact on many people.

When I see this new feature, lots of places that use Dependency Injection[3] come to my focus as candidates to be impacted, such as application or infrastructure service classes. As a result, we will write a much cleaner and leaner code without giving up on good practices to write modular, maintainable and testable software.

The Dependency Inversion Principle[4] gives us decoupling powers. But we know that many classes will receive the same concrete implementation most of (if not all) the time.

So this is very common to see some variation of this code:

$someDependencyToBeInjected = FactoryClass::create();
$someService = new SomeServiceClass($someDependencyToBeInjected);

Important note: I will ignore for now Service Containers and frameworks features that deal with service instantiation, auto wiring, etc.

Think of a database query service class: you depend on a connection object. Every time you need to instantiate your database service class, you need to prepare the connection dependency and inject it at the service class. Database connections are a great example when you use the same concrete implementation more than 90% of the time.

The same applies to a Service class that you use to handle business logic and depends on QueryService and CommandHandler interfaces to do its job.

Before PHP 8.1 we have code like this:

// service class to apply business logic
// most standard
class DefaultLeadRecordService implements LeadRecordService
{
    public function __construct(
        private LeadQueryService $queryService,
        private LeadCommandHandler $commandHandler
    ) {
    }
}

// infrastructure class to match the interface -- a DBAL concrete class
// sneakily allowing a "default" value, but also open to Dependency Injection
// but not that great
class DbalLeadQueryService implements LeadQueryService
{
    public function __construct(private ?Connection $connection = null)
    {
        if (!$this->connection) {
            $this->connection = Core::getConnection();
        }
    }
}

// instantiation would be something like -- given you have $connection already instantiated
$connection =  \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);

$service = new \Blog\Application\DefaultLeadRecordService(
    new \Blog\Infrastructure\DbalLeadQueryService($connection),
    new \Blog\Infrastructure\DbalLeadCommandHandler($connection),
);

// if we allow construct get default value
$service = new \Blog\Application\DefaultLeadRecordService(
    new \Blog\Infrastructure\DbalLeadQueryService(),
    new \Blog\Infrastructure\DbalLeadCommandHandler(),
);

While on PHP 8.1, you will be able to write it like so:

class DefaultLeadRecordService implements LeadRecordService
{
    public function __construct(
        private LeadQueryService $queryService = new DbalLeadQueryService(),
        private LeadCommandHandler $commandHandler = new DbalLeadCommandHandler()
    ) {
    }
}

// we see there is still room for new features here
// still not that great
class DbalLeadQueryService implements LeadQueryService
{
    public function __construct(private ?Connection $connection = null)
    {
        // waiting when `new initializers` feature allows static function as default parameters
        if (!$this->connection) {
            $this->connection = Core::getConnection();
        }
    }
}

$service = new \Blog\Application\DefaultLeadRecordService();

One liner! That saves a lot of typing, and the code remains very well structured. This is the type of significant impact we will have on our day-to-day work. We will write a more straightforward, robust and meaningful code, and we will ship features faster with high-quality code.

If you want to see a full implementation of this, check the code at https://github.com/rafaelbernard/blog-php-81-new-initializers

Test, our faithful friend

Writing tests is a must-have for any repository where quality is a requirement. However, the "New in initializers" feature does not force us to give up on a complete suite of tests. We still have all powers of unit or integration tests.

For application code, we would write unit tests and all the expectations for concrete dependencies:

<?php

namespace Test\Unit\Blog\Application;

use Blog\Application\DefaultLeadRecordService;
use Blog\Domain\LeadCommandHandler;
use Blog\Domain\LeadQueryService;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase;

class DefaultLeadRecordServiceTest extends TestCase
{
    private const EMAIL = '[email protected]';

    private LeadQueryService|MockObject $leadQueryServiceMock;
    private LeadCommandHandler|MockObject $leadCommandHandlerMock;

    private DefaultLeadRecordService $service;

    protected function setUp(): void
    {
        parent::setUp();

        $this->leadQueryServiceMock = $this->getMockBuilder(LeadQueryService::class)->getMock();
        $this->leadCommandHandlerMock = $this->getMockBuilder(LeadCommandHandler::class)->getMock();

        $this->service = new DefaultLeadRecordService($this->leadQueryServiceMock, $this->leadCommandHandlerMock);
    }

    public function testCanAdd()
    {
        $this->leadQueryServiceMock
            ->expects(self::once())
            ->method('getByEmail')
            ->with(self::EMAIL)
            ->willReturn(false);

        $this->leadCommandHandlerMock
            ->expects(self::once())
            ->method('add')
            ->with(self::EMAIL)
            ->willReturn(1);

        $result = $this->service->add(self::EMAIL);

        self::assertEquals(1, $result);
    }

    public function testAddExistentReturnsFalse()
    {
        $this->leadQueryServiceMock
            ->expects(self::once())
            ->method('getByEmail')
            ->with(self::EMAIL)
            ->willReturn(['email' => self::EMAIL]);

        $this->leadCommandHandlerMock
            ->expects(self::never())
            ->method('add');

        $result = $this->service->add(self::EMAIL);

        self::assertFalse($result);
    }

    public function testCanGetAll()
    {
        $unsorted = [
            ['email' => '[email protected]'],
            ['email' => '[email protected]'],
            ['email' => '[email protected]'],
        ];

        $this->leadQueryServiceMock
            ->expects(self::once())
            ->method('getAll')
            ->willReturn($unsorted);

        $fetched = $this->service->getAll();

        $expected = $unsorted;
        asort($expected);

        self::assertEquals($expected, $fetched);
    }
}

Integration tests can be written for infrastructure code. For instance, we can use an SQLite database file to assert the logic for database operations.

Be aware that I am creating an SQLite temp database file on-demand for each test execution with $this->databaseFilePath = '/tmp/test-' . time(); and, thanks to the Dbal library, we can be confident that operations could work for any database.

-> It is highly recommended that, as an alternative, create a container with a seeded database that is compatible with your production database system.

<?php

namespace Test\Integration\Blog\Infrastructure;

use Blog\Infrastructure\DbalLeadQueryService;
use Doctrine\DBAL\Connection;
use Faker\Factory;
use Faker\Generator;
use Test\TestCase;

class DbalLeadQueryServiceTest extends TestCase
{
    private string $databaseFilePath;

    private Generator $faker;
    private Connection $connection;

    private DbalLeadQueryService $service;

    public function testCanGetAll()
    {
        $this->addEmail($email1 = $this->faker->email());
        $this->addEmail($email2 = $this->faker->email());
        $this->addEmail($email3 = $this->faker->email());

        $expected = [
            ['email' => $email1],
            ['email' => $email2],
            ['email' => $email3],
        ];

        $fetched = $this->service->getAll();

        self::assertEquals($expected, $fetched);
    }

    protected function setUp(): void
    {
        parent::setUp();

        $this->faker = Factory::create();

        $this->createLeadTable();

        $this->service = new DbalLeadQueryService($this->connection());
    }

    protected function tearDown(): void
    {
        parent::tearDown();

        $this->dropDatabase();
    }

    private function connection(): Connection
    {
        if (!isset($this->connection)) {
            $this->databaseFilePath = '/tmp/test-' . time();

            $config = new \Doctrine\DBAL\Configuration();
            $connectionParams = [
                'url' => "sqlite:///{$this->databaseFilePath}",
            ];

            $this->connection = DriverManager::getConnection($connectionParams, $config);
        }

        return $this->connection;
    }

    private function dropDatabase()
    {
        @unlink($this->databaseFilePath);
    }

    private function createLeadTable(): void
    {
        $this->connection()->executeQuery('CREATE TABLE IF NOT EXISTS leads ( email VARCHAR )');
    }

    private function addEmail(string $email): int
    {
        return $this->connection()->insert('leads', ['email' => $email]);
    }
}

Conclusion

PHP is evolving very quickly, with new features that enable more quality software, help developers and is even more committed to the fact that most of the web run flavours of PHP code. New features improve readability, software architecture, test coverage and performance. Those are all proof of a mature and live language.

Upgrade to PHP 8.1 and use "new in initializers" as soon as possible. You will not regret it.

If there is something you want to discuss more, let me know in the comments.

Links:

  1. New in initializers RFC
  2. Road to PHP 8.1
  3. Dependency Injection
  4. Dependency inversion principle
  5. Interface segregation principle
  6. Solid relevance
  7. SOLID principles
Categorias
Tropeçando

Tropeçando 104

CASL

CASL (pronounced /ˈkæsəl/, like castle) is an isomorphic authorization JavaScript library which restricts what resources a given client is allowed to access. It's designed to be incrementally adoptable and can easily scale between a simple claim based and fully featured subject and attribute based authorization. It makes it easy to manage and share permissions across UI components, API services, and database queries.

The Danger of Dark Patterns (With Infographic)

Are manipulative design techniques undermining your product and leading users to make bad decisions? Here’s how to avoid dark patterns and create ethical products that enhance customer trust.

Dark patterns are a popular design topic but defining them can be difficult. That’s because they’ve become so prevalent that many have been adopted as design conventions. It’s crucial to understand these manipulative techniques in order to create ethical products that enhance customer trust.

DevOps: Shift Left to Reduce Failure

The term “shift left” refers to a practice in software development in which teams focus on quality, work on problem prevention instead of detection, and begin testing earlier than ever before. The goal is to increase quality, shorten long test cycles and reduce the possibility of unpleasant surprises at the end of the development cycle—or, worse, in production.

Does varchar(n) use less disk space than varchar() or text?

Tl;DR: No. This is a recurrent doubt due to a real difference in many other database systems. But not for PostgreSQL. Although documentation explains that internally, the core system has a wise way to split and store string data internally instead of simply reserving the total space, it is hard to believe. Here we have proof that there is no real difference.

How to ease the pains of testing legacy code?

Practically every programmer in their career struggled with working on a legacy project or one in which at least part of the job involved some kind of legacy code. I will show you some tips and tricks which will make writing unit tests for legacy applications much easier and less hurtful. Let’s go deep into testing legacy code!

Categorias
Miscelaneous

Tropeçando 103

What is Domain-Driven Design (DDD)

A definition of DDD as a software design discipline

How to refactor without overtime and missed deadlines

A lot of software engineers, including myself, are passionate about code quality. This striving for a well-shaped codebase, while getting things done could cost one quite a few hours and nerves, though. I'm constantly looking for ways to achieve these two goals without significant trade-offs. Stand by for the current state.

How to test a PHP app? PHP unit testing and more

Do you really need to create tests? Of course, there are many reasons to do so – improved quality of software, decreased risks while making changes in the code, identifying errors, checking business requirements, improving security…I could go on and on with that. The point is – tests do make a difference.

Application Modernization Isn’t Just Fighting Legacy Tech

When radical innovations were rare, businesses could afford to treat application modernization as a sporadic reaction to change. A decade ago, most organizations modernized only when they were compelled to.

However, in the era of open-source and continuous innovation, modernization can’t be an isolated, one-off project. Businesses need to embrace a culture that celebrates change to thrive in the digital age. According to a report by F5, the past year has witnessed 133% growth in application modernization.

Responsible tech playbook

As technology becomes more central to peoples' lives, and to what businesses do, and how they succeed, the ethics of technology must come into sharper focus.

Despite technology becoming a critical part of what enterprizes do, it's not always clear how to approach and apply technology in an ethical or responsible way.

The Responsible tech playbook is a collection of tools, methods, and frameworks that help you to assess, model and mitigate values and risks of the software you are creating with a special emphasis on the impact of your work on the individual and society.

Categorias
PHP Programação

PHP Memory Usage and Performance Improvements Tips

Memory usage and performance improvements make everybody happier, from end-user to cloud and infrastructure engineers. And they are all right, and this is an optimization that we should try to achieve as much as possible.

I am also keeping this page for a reference to my future self because we cannot rely too much on our memory, and that will be a good reference I want to re-visit. I will make constant updates on this page.

Use objects with declared properties over array

Arrays have a larger footprint to avoid constant memory pointers reassignments. It then reserves large amounts of memory when more elements or indexes are added.

Image for array vs object memory usage

Be careful to self-referencing that would prevent garbage collector from work

Garbage collector is working as expected when the internal reference count (how may times a value is used) reaches zero:

$x = "foobar";    // refcount = 1
$y = $x;            // refcount = 2
unset($x);      // refcount = 1
unset($y);      // refcount = 0 -> garbage collector will be happy ==> Destroy!

But self-referencing can be tricky:

$x = [];            // refcount = 1
$x[0] =& $x;    // refcount = 2
unset($x);      // refcount = 1
                    // It will never come to zero due to cycle

The cycle collector will eventually destroy it, but it will hang on memory for a while anyway.

Sprintf vs double/single quote concatenation

A very common use case is string concatenation or interpolation when you want to add a variable into a static string. It is interesting to note that:

If you have PHP < 7.4, use double-quote interpolation or single quote concatenation over sprintf function.

<?php 

$this->start($loop);

ob_start();

for ($i = 0; $i < $this->loop; ++$i) {
    print 'Lorem '.$i.' ipsum dolor sit amet, consectetur adipiscing elit. Proin malesuada, nisl sit amet congue blandit';
}

ob_end_clean();

return $this->end();

If you have PHP greater than 7.4, use sprintf:

<?php 

$this->start($loop);

for ($i = 0; $i < $this->loop; ++$i) {
    $value = sprintf('Lorem %s ipsum dolor sit amet, consectetur adipiscing elit. Proin malesuada, nisl sit amet congue blandit', $i);
}

return $this->end();

PHP Benchmarking

PHPBench.com was constructed as a way to open people's eyes to the fact that not every PHP code snippet will run at the same speed. You may be surprised at the results that this page generates, but that is ok. This page was also created so that you would be able to find discovery in these statistics and then maybe re-run these tests in your own server environment to play around with this idea yourself, by using the code examples (these code examples are automatically generated and as the code in my .php files change, so do they).

PHP benchmarks and optimizations

Collection of tests and benchmarks for common operations in PHP. Tests run on several versions of PHP. There is an option to compare different solutions for the same problem to compare performances between them, such as checking values with isset against !empty.