PHPackages                             rafalmasiarek/contact-form - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. rafalmasiarek/contact-form

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

rafalmasiarek/contact-form
==========================

Lightweight, pluggable contact form service with hooks, validators and PSR-7-friendly helpers.

v1.2.0(5mo ago)07[1 issues](https://github.com/rafalmasiarek/php-contact-form/issues)MITPHPPHP ^8.0

Since Sep 6Pushed 5mo agoCompare

[ Source](https://github.com/rafalmasiarek/php-contact-form)[ Packagist](https://packagist.org/packages/rafalmasiarek/contact-form)[ RSS](/packages/rafalmasiarek-contact-form/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (1)Versions (5)Used By (0)

ContactForm (PSR‑7 friendly)
============================

[](#contactform-psr7-friendly)

Lightweight, framework-agnostic contact form service for PHP. It gives you a tiny, pluggable pipeline (hooks + validators), a simple DTO for requests, and transport-agnostic email sending (PHPMailer SMTP or native mail()), with example wiring for MailHog. Works with Composer or a standalone autoloader.

Highlights
----------

[](#highlights)

- **Small &amp; decoupled**: no hard HTTP coupling; returns a simple array you can turn into any response.
- **Pluggable pipeline**: run validators (as callables) and hooks (before/after validation, after send, on failure).
- **Clean data model**: ContactData DTO + OutboundEmail builder.
- **Transports**: PHPMailer adapter (SMTP) or native mail() sender.
- **i18n-friendly messages**: resolve human texts via codes with ArrayMessageResolver.
- **PSR-7 friendly**: easy to slot into Slim, Laminas, etc.
- **Batteries included examples**: demo app with MailHog Docker, simple math CAPTCHA (hook + validator), required fields + email validators, IP annotation hook.

> Namespace: `rafalmasiarek\ContactForm` (PSR‑4 autoload).
> PHP: **^8.0**

Installation
------------

[](#installation)

```
composer require rafalmasiarek/contact-form
# or use a local path repo during development
```

If you use the PHPMailer adapter:

```
composer require phpmailer/phpmailer:^6.9
```

Quickstart
----------

[](#quickstart)

```
git clone https://github.com/rafalmasiarek/php-contact-form.git php-contactform
cd php-contactform/examples
docker compose up -d
# open http://localhost:8080

```

Using with composer
-------------------

[](#using-with-composer)

The repo ships a PSR-4 style autoload.php. Point it at src/ (and optional lib/ folders for hooks/validators) and require it in your front controller.

```
require __DIR__ . '/../autoload.php'; // or examples/lib/contactform/autoload.php

```

Example wiring (simplified)
---------------------------

[](#example-wiring-simplified)

```
$cfg = require __DIR__ . '/../config.php';

$resolver = new ArrayMessageResolver([
  'OK_SENT' => ['message' => 'Message sent', 'http' => 200],
  'ERR_VALIDATION' => ['message' => 'Validation error', 'http' => 422],
  'ERR_SEND_FAILED' => ['message' => 'Message could not be sent.', 'http' => 500],
]);

// optional: register default messages for custom validators
ContactForm\Validators\MathCaptchaValidator::registerDefaultMessages($resolver);

$service = (new ContactFormService())
  ->setMessageResolver($resolver)
  ->setHooks([
    new ContactForm\Hook\AnnotateIpHook(),
    new ContactForm\Hook\MathCaptchaHook(
      field: $cfg['captcha']['field'],
      metaKey: $cfg['captcha']['meta_key']
    ),
  ])
  ->setValidators([
    'required' => ContactForm\Validators\FieldsValidator::required(['name','email','message']),
    'email'    => ContactForm\Validators\FieldsValidator::email('email', 'strict'),
    'captcha'  => ContactForm\Validators\MathCaptchaValidator::validate(
      field: $cfg['captcha']['field'],
      sessionKey: $cfg['captcha']['session_key'],
      oneShot: (bool)$cfg['captcha']['one_shot']
    ),
  ]);

// Pick a sender: PHPMailer if available, otherwise native mail()
$sender = class_exists(\PHPMailer\PHPMailer\PHPMailer::class)
  ? new \rafalmasiarek\ContactForm\Mail\PhpMailerEmailSender($cfg['smtp'])
  : new \rafalmasiarek\ContactForm\Mail\NativeMailSender(
      from: $cfg['smtp']['from'],
      fromName: $cfg['smtp']['from_name'],
      to: $cfg['smtp']['to'],
      replyTo: null
    );
$service->setEmailSender($sender);

// Build data and process
$data = new \rafalmasiarek\ContactForm\Model\ContactData(
  name: $_POST['name'] ?? '',
  email: $_POST['email'] ?? '',
  message: $_POST['message'] ?? '',
  subject: $_POST['subject'] ?? '',
  phone: $_POST['phone'] ?? '',
  meta: []
);

echo json_encode($service->process($data));
```

PSR‑7 / Middlewares
-------------------

[](#psr7--middlewares)

Add a middleware in your app that attaches `client` to request attributes and pass it via `withContext()`.

Hooks
-----

[](#hooks)

Implement `ContactFormHook` with any of these optional methods:

- `onBeforeValidate(ContactDataHook $dto)`
- `onAfterValidate(ContactDataHook $dto, string $validatorLabel)`
- `onBeforeSend(ContactDataHook $dto)`
- `onAfterSend(ContactDataHook $dto, string $transportMessageId)`

All hook errors are swallowed by default to protect the main flow.

Email
-----

[](#email)

Use `EmailSenderInterface` abstraction; provided adapters:

- `PhpMailerEmailSenderInterface` (depends on `phpmailer/phpmailer`)

`OutboundEmail` encapsulates the rendered message.

Messages
--------

[](#messages)

`MessageResolverInterface` decouples symbolic codes from UI strings.
`ArrayMessageResolver` is a simple in‑memory map with optional HTTP codes.

Validation
----------

[](#validation)

Any callable validator is accepted. Library provides helper DTO `ContactDataValidator` to keep the code tidy.

Versioning &amp; BC
-------------------

[](#versioning--bc)

- Namespace is stable: `rafalmasiarek\ContactForm`.
- All classes are PSR‑4 autoloaded from `/src`.
- `DefaultIpResolverInterface` keeps a backward‑compatible constructor; prefer `Psr7IpResolverInterface` in PSR‑7 apps.

License
-------

[](#license)

MIT

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance70

Regular maintenance activity

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~39 days

Total

3

Last Release

170d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/17765d36dfdee9f4179c94861184464cb4282d224e9db7fa86b4dff6005c166c?d=identicon)[rafalmasiarek](/maintainers/rafalmasiarek)

---

Top Contributors

[![rafalmasiarek](https://avatars.githubusercontent.com/u/36776423?v=4)](https://github.com/rafalmasiarek "rafalmasiarek (2 commits)")

### Embed Badge

![Health badge](/badges/rafalmasiarek-contact-form/health.svg)

```
[![Health](https://phpackages.com/badges/rafalmasiarek-contact-form/health.svg)](https://phpackages.com/packages/rafalmasiarek-contact-form)
```

###  Alternatives

[google/cloud-core

Google Cloud PHP shared dependency, providing functionality useful to all components.

343121.4M79](/packages/google-cloud-core)[aimeos/aimeos-base

Aimeos base layer for abstracting from host environments

2.1k134.0k1](/packages/aimeos-aimeos-base)[phpgt/dom

Modern DOM API.

12412.2M18](/packages/phpgt-dom)[anthropic-ai/sdk

Anthropic PHP SDK

129134.7k5](/packages/anthropic-ai-sdk)[jaxon-php/jaxon-core

Jaxon is an open source PHP library for easily creating Ajax web applications

73142.3k25](/packages/jaxon-php-jaxon-core)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
