Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Algerian Mobile Phone Number Laravel Package

cherif/algerian-mobile-phone-number

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require cherif/algerian-mobile-phone-number
    
  2. First Use Case Validate and create an Algerian mobile phone number in a Laravel request handler:

    use Cherif\AlgerianMobilePhoneNumber\AlgerianMobilePhoneNumber;
    
    $phoneInput = request()->input('phone');
    $phoneNumber = AlgerianMobilePhoneNumber::fromString($phoneInput);
    
  3. Where to Look First

    • README.md: For basic usage and API reference.
    • Tests: In the tests/ directory for edge cases and validation logic.
    • Source Code: src/AlgerianMobilePhoneNumber.php for implementation details.

Implementation Patterns

Core Workflows

  1. Request Validation Use the package in Laravel's Form Request validation:

    use Cherif\AlgerianMobilePhoneNumber\AlgerianMobilePhoneNumber;
    
    public function rules()
    {
        return [
            'phone' => [
                'required',
                function ($attribute, $value, $fail) {
                    try {
                        AlgerianMobilePhoneNumber::fromString($value);
                    } catch (\InvalidArgumentException $e) {
                        $fail('The '.$attribute.' must be a valid Algerian mobile number.');
                    }
                },
            ],
        ];
    }
    
  2. Domain Modeling Embed the value object in Eloquent models:

    use Cherif\AlgerianMobilePhoneNumber\AlgerianMobilePhoneNumber;
    
    class User extends Model
    {
        protected $casts = [
            'phone_number' => AlgerianMobilePhoneNumber::class,
        ];
    
        public function setPhoneNumberAttribute($value)
        {
            $this->attributes['phone_number'] = AlgerianMobilePhoneNumber::fromString($value);
        }
    }
    
  3. Service Layer Integration Use the package in services to enforce business rules:

    class UserService
    {
        public function registerUser(array $data)
        {
            $phone = AlgerianMobilePhoneNumber::fromString($data['phone']);
    
            if ($phone->isMobilis()) {
                // Apply Mobilis-specific logic
            }
        }
    }
    
  4. API Responses Format phone numbers consistently in API responses:

    return response()->json([
        'phone' => $user->phone_number->asString(),
    ]);
    

Integration Tips

  • Laravel Validation: Extend Laravel's validation rules by creating a custom rule:

    use Cherif\AlgerianMobilePhoneNumber\AlgerianMobilePhoneNumber;
    
    class ValidAlgerianPhone implements Rule
    {
        public function passes($attribute, $value)
        {
            try {
                AlgerianMobilePhoneNumber::fromString($value);
                return true;
            } catch (\InvalidArgumentException $e) {
                return false;
            }
        }
    }
    

    Use it in Form Requests:

    public function rules()
    {
        return [
            'phone' => ['required', new ValidAlgerianPhone],
        ];
    }
    
  • Localization: Store formatted phone numbers in a localized format (e.g., 06 99 00 00 00) for UI display:

    $formattedPhone = preg_replace('/(\d{2})(\d{2})(\d{2})(\d{2})/', '$1 $2 $3 $4', $phone->asString());
    

Gotchas and Tips

Pitfalls

  1. Input Sanitization The package does not sanitize input; ensure user-provided data is trimmed and stripped of non-numeric characters (except spaces/dashes) before passing it to fromString():

    $cleanedPhone = preg_replace('/[^\d\s\-]/', '', trim($input));
    AlgerianMobilePhoneNumber::fromString($cleanedPhone);
    
  2. International Formats While the package supports +213 and 00213, ensure consistency in how international formats are handled across your application. For example:

    // May throw an exception if not handled properly
    AlgerianMobilePhoneNumber::fromString('+213 699 000 000');
    
  3. Immutable Objects The withNumber() method returns a new instance, not a modified one. Avoid assuming in-place updates:

    $newPhone = $phone->withNumber('0799000000'); // $phone remains unchanged
    
  4. Operator Comparison Avoid direct comparison with == or ===; use the equals() method for accurate checks:

    // Unreliable
    if ($phone1 == $phone2) { ... }
    
    // Correct
    if ($phone1->equals($phone2)) { ... }
    

Debugging

  • Validation Errors: Catch InvalidArgumentException to handle invalid phone numbers gracefully:

    try {
        $phone = AlgerianMobilePhoneNumber::fromString($input);
    } catch (\InvalidArgumentException $e) {
        Log::error("Invalid phone number: " . $e->getMessage());
        return back()->withErrors(['phone' => 'Invalid Algerian mobile number.']);
    }
    
  • Unexpected Behavior: If isMobilis(), isDjezzy(), or isOoredoo() return false unexpectedly, verify the phone number's prefix (e.g., 06, 07, 05) matches the expected carrier ranges.

Extension Points

  1. Custom Carrier Logic Extend the class to add support for new carriers or modify existing logic:

    class ExtendedAlgerianMobilePhoneNumber extends AlgerianMobilePhoneNumber
    {
        public function isNewCarrier()
        {
            return str_starts_with($this->asString(), '08');
        }
    }
    
  2. Additional Validation Add custom validation rules by extending the package or wrapping it in a service:

    class AlgerianPhoneValidator
    {
        public function validate($phone)
        {
            $phoneObj = AlgerianMobilePhoneNumber::fromString($phone);
            return $this->checkBlacklist($phoneObj);
        }
    
        private function checkBlacklist(AlgerianMobilePhoneNumber $phone)
        {
            // Custom logic
        }
    }
    
  3. Localization Helpers Create helper methods for common localization needs:

    class PhoneHelper
    {
        public static function formatForUI(AlgerianMobilePhoneNumber $phone)
        {
            return preg_replace('/(\d{2})(\d{2})(\d{2})(\d{2})/', '$1 $2 $3 $4', $phone->asString());
        }
    }
    

Config Quirks

  • No Configuration: The package is stateless and requires no configuration. All logic is encapsulated within the AlgerianMobilePhoneNumber class.
  • Dependency Injection: Since the package is a value object, it can be injected directly into Laravel services or controllers without additional setup.

Performance Tips

  • Caching: Cache validated phone numbers if reused frequently (e.g., in a session or Redis):
    $cacheKey = 'phone_'.$phone->asString();
    $cachedPhone = cache()->get($cacheKey);
    
    if (!$cachedPhone) {
        $cachedPhone = AlgerianMobilePhoneNumber::fromString($input);
        cache()->put($cacheKey, $cachedPhone, now()->addHours(1));
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle