Action command in php

Implementation of Command Pattern in PHP

Command Pattern encapsulates everything needed to execute an action. In this article, we will be going through the command design pattern in PHP.

Command is a very useful design pattern, whose intent is to encapsulate a request as an object. One of the biggest advantages to this pattern is that it decouples the object that invokes the operation from the one that actually knows how to perform it.

Definition

In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action.

The definition of Command provided in the original Gang of Four book on DesignPatterns states:
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations

Show Me The Code!

To demonstrate how the Command Pattern works, let’s have a look at an abstract PHP class which implements the PHP Interface class. Here’s the definition of the AbstractCommand class:

In AbstractCommand class, there is one abstract method processCommand and should be implemented to execute a particular command. Let’s do a real world example using the abstract class.

execute () Method:

Method uses following methods:

execute () method invokes pre and post execution methods, processes command, sets the response and finally returns the object ($this). Class object is returned to leverage method chaining and with the help of method chaining we can call more than one method of the class in single instruction.

Signup Command and Usage

Summary

In this post we explore the Command pattern with one real world example. Although the example in this post is simple one, the purpose was to communicate the basic concept rather than a full explanation of every single usage scenario.

References

To know more about command pattern and design patterns. Have a look at following resources:

Share This Post

About Me

WordPress is my daily routine — I am in love with WordPress. I believe my 10+ years of experience can be utilized to provide crafty solutions./

Connect with me

Certified WordPress Expert

Источник

Помогите разобраться с Action в form?

Собственно, вопрос такой: пользователь вводит свои данные (логин и пароль) на index.php, к примеру. Каким образом необходимо задать action и организовать авторизацию, чтобы не перенаправлять авторизацию в другой файл, а обработать ее в index.php?

Читайте также:  Расширенные операторы присваивания python

Что-то такого типа? То есть, по нажатию кнопки, будем вызывать php-функцию внутри index.php?

DevMan

onsubmit – событие javascript и никакого отношения к PHP не имеет.

Что касается вашего вопроса, то разместите код проверки логина в index.php.
Ваша форма:

По нажатию на «Enter», Форма будет отправлять, Но php не будет обрабатывать. Как это можно исправить?

Помоему автор не совсем удачно задал вопрос.

Для любого программиста замена action и «не перенаправлять авторизацию в другой файл, а обработать ее в index.php» означает: вместо запроса к login.php сделать запрос к index.php и внутри него подгрузить модуль авторизации.
В этом случае ответ DevMan вполне себе приемлемое решение.

Но наличие onsubmit=«check_dataLogin()» настораживает и наводит на мысль, что автор все таки хочет прикрутить авторизацию через ajax.

Конкретные примеры кода приводить не буду, ибо вы не указали пользуетесь каким либо JS фреймворком или пишите все от руки в ноутпэде.

Могу только обратить внимание на несколько подводных камней.
1. ваша функуция check_dataLogin() должна всегда возвращать false, в противном случае после того как она отработает бразуер пошлет стандартный post запрос на сервер (не ajax)
2. оставьте form action=login.php. это ваш fallback на случай если в браузере отключен JavaScript.
3. результат у login.php должен личный для обыного post запроса и для ajax: может быть редирект на index.php, либо снова форма логина ( если пароль не верный), или же json для вашего ajax запроса (а может и не json, как реализуете так и будет)

П.С. Я человек новый на хабре и не совсем уверен что в Q&A это у местно, но в мирей айти есть некая этика как задавать вопросы. Практически на всех irc каналах или maillist, в которых я учавствую, подобный вопрос могут проигнорирывать или заклевать вас за «отсутсвие культуры общения». Если повезет с вами сыграют в 10 вопросов, пытаясь выяснить чего же вы все таки добиваетесь.
Для того чтобы вам помогали, ответы были развернутые и быстрые, научитесь формулирывать вопросы в понятной для других форме. Ведь не даром говорят что правильно поставленный вопрос содержит в себе половину ответа.

может это поможет вам goo.gl/EiskH
и еще (без перевода прадва) whathaveyoutried.com

Спасибо!
Очень развернутый ответ! 🙂

К теме Q&A. Я не очень хорошо владею терминологией в веб-разработке. Поэтому вопрос показался, наверное, некорректным. Я попробую еще раз:

на одном из своих проектов я делал авторизацию таким образом:

Файл authorization.php

 0) < $_SESSION['flag'] = true; $_SESSION['user'] = $_POST['login']; $_SESSION['password'] = md5($_POST['password']); $login = $_SESSION['user']; $adminLogin = "admin"; if($login == $adminLogin ) < echo " "; > else echo " "; > else < echo " Authorization   

An incorrect user name or password.

"; > ?>

Такой подход создает очень много php-файлов с одной функцией. Я и подумал: «а что если авторизовывать пользователя в том же php-файле, не создавая кучу этих самых файлов с одной функцией?»

Источник

How to build GitHub Actions in PHP with Minicli and Docker

Pull request automatically created by this workflow + action

GitHub Actions facilitates creating CI/CD automated workflows that can be triggered by GitHub events, such as when a pull request is created, a merge is made, or a new comment is posted on an issue. What some people may not know is that you can also run GitHub actions at scheduled times, based on cron expressions. Public repositories get unlimited GitHub Actions for free, which makes this feature a really great tool for open source and personal projects that must run scheduled tasks. In this guide, you’ll learn how to use GitHub Actions to periodically run a PHP command line application built with Minicli. This application will update a CONTRIBUTORS file in the same repository where the workflow action is set, updating information about top contributors of a project. We’ll implement the repository update portion using the update-files-on-github action, which will generate a commit with the file change to the repository where the workflow is run.

Prerequisites

  • A PHP command line environment ( php-cli , no need for web servers) and Composer installed. The php-curl extension is required to connect to the GitHub API.
  • An empty GitHub repository where you’re going to set up your action. For more info, check this documentation.

Step 1: Bootstrapping the application

Start by bootstrapping a new Minicli application. This will be a single-command application, so we don’t need to use the minicli/application template. Create a new folder and require minicli/minicli to start building your command:

cd ~ mkdir action-contributors cd action-contributors composer require minicli/minicli 

This will create a new composer.json file and download the base minicli/minicli package.
Next, you need to create the entry point script that runs your command. Using your code editor of choice, create a new file in the root of the application called minicli (or another name of your choice):

Include the following code, which bootstraps a Minicli application with a single command defined as callback:

#!/usr/bin/php  if(php_sapi_name() !== 'cli')  exit; > require __DIR__ . '/vendor/autoload.php'; use Minicli\App; $app = new App([ 'app_path' => __DIR__ . '/app/Command' ]); $app->registerCommand('update-contributors', function () use ($app)  $app->getPrinter()->info('Fetching top contributors. '); >); $app->runCommand($argv); 

Save and close the file. Then, run the following command to make this script executable:

Now you can test your command with:

./minicli update-contributors 

screenshot showing the output from the command in the terminal

In the next step, you’ll update the example command to pull the top contributors of a GitHub project, and generate a markdown file with the list.

Step 2: Pulling contributors with the GitHub API

To make requests to the GitHub API, we’ll use the Curly Minicli extension. You can import it to your project with the following command:

composer require minicli/curly 

Obtaining the top contributors for an open source project on GitHub doesn’t require an authentication token. You only need to include a couple headers in your request:

You’ll now edit the update-contributors command to query the GitHub API and save information about top contributors in the project of your choice.

Replace the current content in your minicli script with the following, updated code:

#!/usr/bin/php  if(php_sapi_name() !== 'cli')  exit; > require __DIR__ . '/vendor/autoload.php'; use Minicli\App; use Minicli\Curly\Client; $app = new App([ 'app_path' => __DIR__ . '/app/Command', 'repository' => getenv('CONTRIB_REPOSITORY') ?: 'minicli/minicli', 'output_file' => getenv('CONTRIB_OUTPUT_FILE') ?: 'CONTRIBUTORS.md' ]); $app->registerCommand('update-contributors', function () use ($app)  $app->getPrinter()->info('Fetching top contributors. '); $client = new Client(); $response = $client->get( "https://api.github.com/repos/" . $app->config->repository. "/contributors", ['Accept: application/vnd.github.v3+json', 'User-Agent: Curly'] ); if ($response['code'] != 200)  $app->getPrinter()->error("an error occurred: " . $response['code']); return 1; > $content = "#Contributors\n\n"; $content .= "Shout out to our top contributors!\n\n"; foreach (json_decode($response['body']) as $item)  $content .= "- [$item->login]($item->url)\n"; > try  $contrib_file = fopen($app->config->output_file, 'w+'); fwrite($contrib_file, $content); fclose($contrib_file); > catch (Exception $exception)  $app->getPrinter()->error("An error occurred while trying to save the contrib file."); return 1; > $app->getPrinter()->success("Finished updating contrib file."); return 0; >); $app->runCommand($argv); 

The updated code defines a couple configuration variables: repository and output_file , with default values set to minicli/minicli and CONTRIBUTORS.md respectively. When building your action workflow, you can overwrite these default values with environment variables named CONTRIB_REPOSITORY and CONTRIB_OUTPUT_FILE , respectively.

The update-contributors method now uses a Curly/Client client to query the GitHub API using the endpoint https://api.github.com/repos/owner/repo/contributors . When the request is successful, the application builds a markdown text with the contributors that are returned as response, and writes it to the file defined by the output_file configuration value.

Now run the application again with:

./minicli update-contributors 

Источник

Оцените статью