Installation Add the package via Composer:
composer require clevis/push-notifications:~0.1-beta
Enable the extension in config.neon:
extensions:
pushNotifications: Clevis\PushNotifications\DI\PushNotificationsExtension
Configure Credentials
Update config.neon with your provider credentials (e.g., GCM, APNs, or C2DM):
pushNotifications:
android:
gcm:
apiKey: "YOUR_GCM_API_KEY"
apple:
sandbox: true
pem: "%appDir%/path/to/certificate.pem"
passphrase: "YOUR_PASSPHRASE"
First Push
Inject the Notifications service and send a test message:
use Clevis\PushNotifications\Message\iOSMessage;
use Clevis\PushNotifications\Notifications;
class PushService
{
public function __construct(private Notifications $sender) {}
public function sendTestNotification()
{
$message = new iOSMessage();
$message->setMessage("Hello, World!")
->setDeviceToken("DEVICE_TOKEN_HERE");
$this->sender->send($message);
}
}
Message Creation
Use platform-specific message classes (iOSMessage, AndroidMessage, BlackberryMessage):
$message = new iOSMessage();
$message->setMessage("Your notification text")
->setBadge(5)
->setSound("default")
->setCustomData(['key' => 'value']);
Sending Notifications
Inject Notifications and call send():
$this->sender->send($message);
Batch Sending Loop through device tokens and send multiple messages:
foreach ($deviceTokens as $token) {
$message = new iOSMessage();
$message->setDeviceToken($token)
->setMessage("Custom message for $token");
$this->sender->send($message);
}
Error Handling Wrap sends in try-catch to handle exceptions (e.g., invalid tokens, API failures):
try {
$this->sender->send($message);
} catch (\Exception $e) {
Log::error("Push failed: " . $e->getMessage());
}
Dependency Injection
Bind the Notifications service in your DI container (Nette) for reusable access:
$container->addService('pushSender', $this->sender);
Queueing Offload sends to a queue (e.g., Nette Queue) for async processing:
$queue->enqueue(new PushNotificationJob($message));
Logging Log successful/failed sends for debugging:
$this->sender->send($message, function ($success, $response) {
if (!$success) {
Log::error("Push failed: " . $response);
}
});
Environment-Specific Config
Use %env() for credentials in config.neon:
pushNotifications:
apple:
pem: "%env(PUSH_CERT_PATH)%"
Certificate Paths
pem config may break. Use forward slashes or raw strings:
pem: "C:/path/to/cert.pem" # or "%appDir%/path/to/cert.pem"
use_multi_curl: false in GCM config for Windows.Device Tokens
if (!preg_match('/^[0-9a-f]{64}$/', $deviceToken)) {
throw new \InvalidArgumentException("Invalid token");
}
APNs Sandbox vs. Production
sandbox: true/false may cause deliveries to fail.apple:
sandbox: %env(PUSH_SANDBOX)% # true/false
Rate Limits
// Send in chunks of 100
array_chunk($tokens, 100, function ($chunk) {
foreach ($chunk as $token) { /* send */ }
});
Enable Verbose Logging Add a callback to inspect responses:
$this->sender->send($message, function ($success, $response) {
var_dump($response); // Check raw API response
});
Test with Sandbox
Always test iOS pushes in sandbox (sandbox: true) before production.
GCM Debugging Use the GCM Developer Console to check delivery status.
Custom Message Classes
Extend AbstractMessage to add platform-specific fields:
class CustomMessage extends AbstractMessage {
public function setCustomField($key, $value) {
$this->customData[$key] = $value;
return $this;
}
}
Add New Providers
Implement ProviderInterface for unsupported platforms (e.g., Firebase Cloud Messaging):
class FirebaseProvider implements ProviderInterface {
public function send(Message $message) { /* ... */ }
}
Override Default Behavior
Bind a custom Notifications service in DI to replace the default:
$container->addService('pushSender', new CustomNotifications($provider));
Use Environment Variables
Store sensitive keys in .env and load via %env():
pushNotifications:
android:
gcm:
apiKey: "%env(GCM_API_KEY)%"
Validate Config Early
Add a bootstrapping check in Bootstrap.php:
if (!$this->config->pushNotifications->apple->pem) {
throw new \RuntimeException("APNs certificate path not configured!");
}
Monitor Delivery Track sent notifications in a database for analytics:
$this->sender->send($message, function ($success, $response) {
PushLog::create([
'device_token' => $message->getDeviceToken(),
'status' => $success ? 'sent' : 'failed',
'response' => $response
]);
});
How can I help you explore Laravel packages today?