sábado, 28 de mayo de 2022

Cómo instalar pgAdmin4 en Ubuntu 20.04

 

Introducción

pgAdmin es una alternativa más avanzada que phppgadmin. Es la plataforma de administración de código abierto más popular y rica en funciones para el servidor de base de datos PostgreSQL. Que está disponible para los sistemas operativos Linux, Unix, macOS y Windows.

pgAdmin 4 es la versión mejorada y es una reescritura completa de pgAdmin. Eso incluye una versión de escritorio escrita en NWjs y una aplicación web que se puede implementar directamente en un servidor web. La versión de escritorio le ayuda a acceder a ella desde la máquina local, mientras que el servidor web le permite acceder a ella desde el sistema remoto.

En este tutorial, aprenderá a instalar pgAdmin 4 en sistemas Ubuntu. También incluya los pasos para agregar el servidor PostgreSQL a pgAdmin.

Prerrequisitos

Un sistema Ubuntu 20.04 LTS en ejecución.

Suponiendo que tiene un servidor PostgreSQL preinstalado en su sistema. De lo contrario, consulte el tutorial para instalar PostgreSQL en Ubuntu 20.04 LTS Focal Fossa.

Instalar pgAdmin4 en Ubuntu

Un PPA oficial está disponible para que pgAdmin4 instale la última versión en los sistemas Ubuntu.

Primero, importe la clave GPG de firma del repositorio y agregue el PPA pgAdmin4 a su sistema usando los siguientes comandos.

curl https://www.pgadmin.org/static/packages_pgadmin_org.pub | sudo apt-key add -
sudo sh -c 'echo "deb https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/focal pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list'

Después de agregar el PPA , actualice el caché de Apt e instale el paquete pgAdmin4 en su sistema.

sudo apt update
sudo apt install pgadmin4 

El paquete pgadmin4 contiene ambas versiones de pgadmin4-webpgadmin4-desktop:

  • pgadmin4-web : proporciona la interfaz web accesible en un navegador web
  • pgadmin4-desktop : proporciona una aplicación de escritorio para el sistema Ubuntu, que requiere el sistema de escritorio Ubuntu.

Para instalar en un servidor remoto (por lo tanto, sin un escritorio disponible) use solo el paquete "pgadmin4-web". Para el sistema local con Desktop instalado, se pueden utilizar ambas versiones.

Configurar pgAdmin4-Web

Los usuarios que tienen pgadmin4-web o ambas ediciones instaladas, deben ejecutar el siguiente comando para configurarlo. Esto agregará una pantalla de inicio de sesión al panel web pgAdmin4.

sudo /usr/pgadmin4/bin/setup-web.sh 

El script anterior le pedirá que cree un usuario para acceder a la interfaz web. Ingrese una dirección de correo electrónico y una contraseña cuando se le solicite. Escriba "y" para otras confirmaciones requeridas por el guión.

Una vez finalizado el script, puede acceder al panel web de pgAdmin.

Inicie sesión en el panel pgAdmin4

Los comandos anteriores también configurarán pgAdmin4 con el servidor web Apache. Puede acceder a pgAdmin4 en un navegador web con la siguiente URL: http://server_ip/pgadmin4 .

Asegúrese de cambiar server_ip a localhost, el nombre de dominio apuntado al sistema o la dirección IP del sistema.

En cualquier caso, la página anterior no se carga, reinicie el servidor Apache usando sudo systemctl restart apache2. Vuelva a cargar el panel web.

Ahora inicie sesión con la dirección de correo electrónico y la contraseña configuradas con el script /usr/pgadmin4/bin/setup-web.sh. Después de iniciar sesión correctamente en pgAdmin4, verá el panel de control.

Agregue el servidor PostgreSQL a pgAdmin4

Después de iniciar sesión correctamente en la interfaz web pgAdmin4. Comencemos a agregar instancias de PostgreSQL a pgAdmin4. Puede agregar varios servidores de bases de datos que se ejecutan en la máquina local y en un host remoto.

Para agregar un nuevo servidor, haga clic en el botón " Agregar nuevo servidor ".

Se abrirá una ventana emergente, ingrese un nombre.

Cambie a la pestaña de conexión. Ingrese el nombre de host del servidor PostgreSQL. Utilice "localhost" para ejecutar la base de datos en la misma instancia. Luego ingrese sus detalles de autenticación.

Haga clic en "Guardar" para completar la conexión.

En caso de una autenticación exitosa, verá las bases de datos en la barra lateral como se muestra a continuación.

Ha agregado correctamente el servidor de base de datos de Postgres a pgAdmin4. También puede agregar varias instancias de base de datos a un solo servidor pgAdmin4.

Conclusión

Este tutorial le ayudó a instalar y configurar pgAdmin4 en un sistema Linux Ubuntu 20.04 LTS Focal Fossa. También se agregó un servidor de base de datos que se ejecuta en el mismo host.

How To Install and Use Composer on Ubuntu 20.04

 

How To Install and Use Composer on Ubuntu 20.04

Published on May 4, 2020 · Updated on March 18, 2022
Default avatar
By Erika Heidi
Developer Advocate
How To Install and Use Composer on Ubuntu 20.04
Not using Ubuntu 20.04?Choose a different version or distribution.

Introduction

Composer is a popular dependency management tool for PHP, created mainly to facilitate installation and updates for project dependencies. It will check which other packages a specific project depends on and install them for you, using the appropriate versions according to the project requirements. Composer is also commonly used to bootstrap new projects based on popular PHP frameworks, such as Symfony and Laravel.

In this tutorial, you’ll install and get started with Composer on an Ubuntu 20.04 system.

Prerequisites

In order to follow this guide, you will need access to an Ubuntu 20.04 server as a non-root sudo user, and a firewall enabled on your server. To set this up, you can follow our initial server setup guide for Ubuntu 20.04.

If you would prefer to follow this tutorial using a terminal in your browser, click the Launch an Interactive Terminal! button to get started. You’ll be able to experiment with and run all the commands directly in your browser.

Step 1 — Installing PHP and Additional Dependencies

In addition to dependencies that should be already included within your Ubuntu 20.04 system, such as git and curl, Composer requires php-cli in order to execute PHP scripts in the command line, and unzip to extract zipped archives. We’ll install these dependencies now.

First, update the package manager cache by running:

  1. sudo apt update

Next, run the following command to install the required packages:

  1. sudo apt install php-cli unzip

You will be prompted to confirm installation by typing Y and then ENTER.

Once the prerequisites are installed, you can proceed to installing Composer.

Step 2 — Downloading and Installing Composer

Composer provides an installer script written in PHP. We’ll download it, verify that it’s not corrupted, and then use it to install Composer.

Make sure you’re in your home directory, then retrieve the installer using curl:

  1. cd ~
  2. curl -sS https://getcomposer.org/installer -o /tmp/composer-setup.php

Next, we’ll verify that the downloaded installer matches the SHA-384 hash for the latest installer found on the Composer Public Keys / Signatures page. To facilitate the verification step, you can use the following command to programmatically obtain the latest hash from the Composer page and store it in a shell variable:

  1. HASH=`curl -sS https://composer.github.io/installer.sig`

If you want to verify the obtained value, you can run:

  1. echo $HASH
Output
e0012edf3e80b6978849f5eff0d4b4e4c79ff1609dd1e613307e16318854d24ae64f26d17af3ef0bf7cfb710ca74755a

Now execute the following PHP code, as provided in the Composer download page, to verify that the installation script is safe to run:

  1. php -r "if (hash_file('SHA384', '/tmp/composer-setup.php') === '$HASH') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

You’ll see the following output:

Output
Installer verified

If the output says Installer corrupt, you’ll need to download the installation script again and double check that you’re using the correct hash. Then, repeat the verification process. When you have a verified installer, you can continue.

To install composer globally, use the following command which will download and install Composer as a system-wide command named composer, under /usr/local/bin:

  1. sudo php /tmp/composer-setup.php --install-dir=/usr/local/bin --filename=composer

You’ll see output similar to this:

Output
All settings correct for using Composer Downloading... Composer (version 2.2.9) successfully installed to: /usr/local/bin/composer Use it: php /usr/local/bin/composer

To test your installation, run:

  1. composer
Output
______ / ____/___ ____ ___ ____ ____ ________ _____ / / / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/ / /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ / \____/\____/_/ /_/ /_/ .___/\____/____/\___/_/ /_/ Composer version Composer version 2.2.9 2022-03-15 22:13:37 Usage: command [options] [arguments] Options: -h, --help Display this help message -q, --quiet Do not output any message -V, --version Display this application version --ansi Force ANSI output --no-ansi Disable ANSI output -n, --no-interaction Do not ask any interactive question --profile Display timing and memory usage information --no-plugins Whether to disable plugins. -d, --working-dir=WORKING-DIR If specified, use the given directory as working directory. --no-cache Prevent use of the cache -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug ...

This verifies that Composer was successfully installed on your system and is available system-wide.

Note: If you prefer to have separate Composer executables for each project you host on this server, you can install it locally, on a per-project basis. This method is also useful when your system user doesn’t have permission to install software system-wide.

To do this, use the command php /tmp/composer-setup.php. This will generate a composer.phar file in your current directory, which can be executed with php composer.phar.

Now let’s look at using Composer to manage dependencies.

Step 3 — Using Composer in a PHP Project

PHP projects often depend on external libraries, and managing those dependencies and their versions can be tricky. Composer solves that problem by keeping track of project versions and dependencies, while also facilitating the process of finding, installing, and updating packages that are required by a project.

In order to use Composer in your project, you’ll need a composer.json file. The composer.json file tells Composer which dependencies it needs to download for your project, and which versions of each package are allowed to be installed. This is extremely important to keep your project consistent and avoid installing unstable versions that could potentially cause backwards compatibility issues.

You don’t need to create this file manually - it’s common to run into syntax errors when you do so. Composer offers an interactive way to create a new composer.json file based on the user’s input, which is a good choice if you plan on sharing your project later as a public package on Packagist. Composer also auto-generates a barebones composer.json file when you run a composer require command to include a dependency in a newly created project.

The process of using Composer to install a package as dependency in a project involves the following steps:

  • Identify what kind of library the application needs.
  • Research a suitable open source library on Packagist.org, the official package repository for Composer.
  • Choose the package you want to depend on.
  • Run composer require to include the dependency in the composer.json file and install the package.

Let’s try this out with a demo application.

The goal of this application is to transform a given sentence into a URL-friendly string - a slug. This is commonly used to convert page titles to URL paths (like the final portion of the URL for this tutorial).

Let’s start by creating a directory for our project. We’ll call it slugify:

  1. cd ~
  2. mkdir slugify
  3. cd slugify

Although not required, you could now run a composer init command to create a detailed composer.json file for your project. Because our project’s only objective is to demonstrate how to install dependencies with Composer, we’ll use a simpler composer.json file that will be auto-generated when we require our first package.

Now it’s time to search Packagist.org for a package that can help us generate slugs. If you search for the term “slug” on Packagist, you’ll get a result similar to this:

Packagist Search Results for the term "slug"

You’ll see two numbers on the right side of each package in the list. The number on the top represents how many times the package was installed via Composer, and the number on the bottom shows how many times a package was starred on GitHub. Generally speaking, packages with more installations and more stars tend to be more stable, since so many people are using them. It’s also important to check the package description for relevance to make sure it’s what you need.

We need a string-to-slug converter. From the search results, the package cocur/slugify, which appears as the first result in that page, seems to be a good match, with a reasonable amount of installations and stars.

Packages on Packagist have a vendor name and a package name. Each package has a unique identifier (a namespace) in the same format GitHub uses for its repositories: vendor/package. The library we want to install uses the namespace cocur/slugify. You need a package’s namespace in order to require it in your project.

Now that you know exactly which package you want to install, you can run composer require to include it as a dependency and also generate the composer.json file for your project. One thing that is important to notice when requiring packages is that Composer tracks both application-level dependencies as well as system-level dependencies. System-level dependencies are important to indicate which PHP modules a package relies on. In the case of the cocur/slugify package, it requires a PHP module that we haven’t installed yet.

When a required package relies on a system library that is currently not installed on your server, you will get an error telling which requirement is missing:

  1. composer require cocur/slugify
Output
Using version ^4.0 for cocur/slugify ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Your requirements could not be resolved to an installable set of packages. Problem 1 - Installation request for cocur/slugify ^4.0 -> satisfiable by cocur/slugify[v4.0.0]. - cocur/slugify v4.0.0 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system. ...

To solve the system dependency problem, we can search for the missing package using apt search:

  1. apt search mbstring
Output
Sorting... Done Full Text Search... Done php-mbstring/focal 2:7.4+75 all MBSTRING module for PHP [default] php-patchwork-utf8/focal 1.3.1-1 all UTF-8 strings handling for PHP php7.4-mbstring/focal 7.4.3-4ubuntu1 amd64 MBSTRING module for PHP

After locating the correct package name, you can use apt once again to install the system dependency:

  1. sudo apt install php-mbstring

Once the installation is finished, you can run the composer require command again:

  1. composer require cocur/slugify
Output
Using version ^4.0 for cocur/slugify ./composer.json has been created Loading composer repositories with package information Updating dependencies (including require-dev) Package operations: 1 install, 0 updates, 0 removals - Installing cocur/slugify (v4.0.0): Downloading (100%) Writing lock file Generating autoload files

As you can see from the output, Composer automatically decided which version of the package to use. If you check your project’s directory now, it will contain two new files: composer.json and composer.lock, and a vendor directory:

  1. ls -l
Output
total 12 -rw-rw-r-- 1 sammy sammy 59 May 4 13:56 composer.json -rw-rw-r-- 1 sammy sammy 3229 May 4 13:56 composer.lock drwxrwxr-x 4 sammy sammy 4096 May 4 13:56 vendor

The composer.lock file is used to store information about which versions of each package are installed, and ensure the same versions are used if someone else clones your project and installs its dependencies. The vendor directory is where the project dependencies are located. The vendor folder shouldn’t be committed into version control - you only need to include the composer.json and composer.lock files.

When installing a project that already contains a composer.json file, run composer install in order to download the project’s dependencies.

Let’s take a quick look at version constraints. If you check the contents of your composer.json file, you’ll see something like this:

  1. cat composer.json
Output
{ "require": { "cocur/slugify": "^4.0" } }

You might notice the special character ^ before the version number in composer.json. Composer supports several different constraints and formats for defining the required package version, in order to provide flexibility while also keeping your project stable. The caret (^) operator used by the auto-generated composer.json file is the recommended operator for maximum interoperability, following semantic versioning. In this case, it defines 4.0 as the minimum compatible version, and allows updates to any future version below 5.0.

Generally speaking, you won’t need to tamper with version constraints in your composer.json file. However, some situations might require that you manually edit the constraints–for instance, when a major new version of your required library is released and you want to upgrade, or when the library you want to use doesn’t follow semantic versioning.

Here are some examples to give you a better understanding of how Composer version constraints work:

ConstraintMeaningExample Versions Allowed
^1.0>= 1.0 < 2.01.0, 1.2.3, 1.9.9
^1.1.0>= 1.1.0 < 2.01.1.0, 1.5.6, 1.9.9
~1.0>= 1.0 < 2.0.01.0, 1.4.1, 1.9.9
~1.0.0>= 1.0.0 < 1.11.0.0, 1.0.4, 1.0.9
1.2.11.2.11.2.1
1.*>= 1.0 < 2.01.0.0, 1.4.5, 1.9.9
1.2.*>= 1.2 < 1.31.2.0, 1.2.3, 1.2.9

For a more in-depth view of Composer version constraints, see the official documentation.

Next, let’s look at how to load dependencies automatically with Composer.

Step 4 — Including the Autoload Script

Since PHP itself doesn’t automatically load classes, Composer provides an autoload script that you can include in your project to get autoloading working for your project. This file is automatically generated by Composer when you add your first dependency.

The only thing you need to do is include the vendor/autoload.php file in your PHP scripts before any class instantiation.

Let’s try it out in our demo application. Open a new file called test.php in your text editor:

  1. nano test.php

Add the following code which brings in the vendor/autoload.php file, loads the cocur/slugify dependency, and uses it to create a slug:

test.php
<?php
require __DIR__ . '/vendor/autoload.php';

use Cocur\Slugify\Slugify;

$slugify = new Slugify();

echo $slugify->slugify('Hello World, this is a long sentence and I need to make a slug from it!');

Save the file and exit your editor.

Now run the script:

  1. php test.php

This produces the output hello-world-this-is-a-long-sentence-and-i-need-to-make-a-slug-from-it.

Dependencies need updates when new versions come out, so let’s look at how to handle that.

Step 5 — Updating Project Dependencies

Whenever you want to update your project dependencies to more recent versions, run the update command:

  1. composer update

This will check for newer versions of the libraries you required in your project. If a newer version is found and it’s compatible with the version constraint defined in the composer.json file, Composer will replace the previous version installed. The composer.lock file will be updated to reflect these changes.

You can also update one or more specific libraries by specifying them like this:

  1. composer update vendor/package vendor2/package2

Be sure to check in your composer.json and composer.lock files within your version control system after you update your dependencies so that others can install these newer versions too.

Conclusion

Composer is a powerful tool that can greatly facilitate the work of managing dependencies in PHP projects. It provides a reliable way of discovering, installing, and updating PHP packages that a project depends on. In this guide, we saw how to install Composer, how to include new dependencies in a project, and how to update these dependencies once new versions are available.