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

Predictionio Laravel Package

predictionio/predictionio

Apache PredictionIO is an open-source machine learning server for building predictive engines quickly. It integrates data collection, model training, and deployment, with support for event ingestion, scalable backends, and custom algorithms for recommendations and classification.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

To integrate PredictionIO (now archived) into a Laravel application, follow these steps:

  1. Install the PredictionIO Engine

    • Deploy PredictionIO on a server (Docker recommended):
      docker run -d -p 8000:8000 predictionio/predictionio-engine:0.11.0
      
    • Configure the engine via conf/engine.json (adjust appId, storageContext, etc.).
  2. Laravel HTTP Client Setup Install Guzzle for API calls:

    composer require guzzlehttp/guzzle
    
  3. First API Call (Event Tracking) Create a helper class (app/Services/PredictionIOService.php):

    use GuzzleHttp\Client;
    
    class PredictionIOService {
        protected $client;
    
        public function __construct() {
            $this->client = new Client([
                'base_uri' => 'http://localhost:8000/ps/',
            ]);
        }
    
        public function trackEvent($userId, $event) {
            $response = $this->client->post('events', [
                'json' => [
                    'user' => $userId,
                    'event' => $event,
                    'properties' => ['timestamp' => now()->toDateTimeString()]
                ]
            ]);
            return json_decode($response->getBody(), true);
        }
    }
    
  4. Trigger an Event in a Controller

    use App\Services\PredictionIOService;
    
    class UserController extends Controller {
        public function logAction(User $user) {
            $predictionIO = new PredictionIOService();
            $predictionIO->trackEvent($user->id, 'user:viewed:product');
        }
    }
    

Implementation Patterns

Workflow: Real-Time Recommendations

  1. Event Tracking Log user actions (e.g., product:view, purchase) via the trackEvent method.

    $predictionIO->trackEvent($userId, 'product:view', ['productId' => 123]);
    
  2. Query Recommendations Use the query endpoint to fetch recommendations:

    public function getRecommendations($userId, $num = 5) {
        $response = $this->client->post('query', [
            'json' => [
                'user' => $userId,
                'num' => $num
            ]
        ]);
        return json_decode($response->getBody(), true)['result']['itemScores'];
    }
    
  3. Batch Processing For offline training, use the import endpoint to bulk-insert events:

    public function importEvents(array $events) {
        $response = $this->client->post('import', [
            'json' => ['events' => $events]
        ]);
        return $response->getStatusCode() === 200;
    }
    

Integration Tips

  • Queue Delayed Events Use Laravel Queues to defer event tracking (e.g., for analytics):

    dispatch(new TrackPredictionIOEvent($userId, 'delayed:event'));
    
  • Cache Recommendations Cache API responses to reduce latency:

    return Cache::remember("predio:recommendations:{$userId}", now()->addHours(1), function() use ($userId) {
        return $this->getRecommendations($userId);
    });
    
  • Model Binding Extend Laravel’s Eloquent models to auto-track events:

    class Product extends Model {
        public function save(array $options = []) {
            event(new ProductViewed($this));
            return parent::save($options);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated API PredictionIO’s API is outdated (last release: 2016). Use ps/ prefix for endpoints (e.g., /ps/events).

    • Fix: Always prefix URLs with /ps/ in the base URI.
  2. Event Schema Mismatch Events must match the template defined in conf/event_schema.json. Invalid schemas return 400 Bad Request.

    • Debug: Validate events against the schema before sending.
  3. Engine Restarts Changes to event_schema.json or models require engine restarts:

    docker restart predictionio-engine
    
  4. Rate Limiting The engine may throttle requests. Monitor logs (logs/engine.out) for 429 Too Many Requests.

Debugging

  • Check Engine Logs Access logs via Docker:

    docker logs predictionio-engine
    

    Look for errors like Invalid event schema.

  • Validate JSON Payloads Use json_last_error() to debug malformed requests:

    $data = ['user' => $userId, 'event' => $event];
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new \Exception("Invalid JSON: " . json_last_error_msg());
    }
    

Extension Points

  1. Custom Algorithms Extend PredictionIO’s src/main/scala/engine (Scala) for custom recommenders. Rebuild the engine:

    sbt assembly
    
  2. Webhooks Use Laravel’s HandleIncomingWebhook to process PredictionIO’s real-time updates (if configured).

  3. Fallback Logic Implement a fallback for API failures:

    try {
        return $this->getRecommendations($userId);
    } catch (\Exception $e) {
        return Cache::get("fallback:recommendations:{$userId}", []);
    }
    

Config Quirks

  • Storage Backend Defaults to H2 (in-memory). For production, switch to Postgres in conf/storage_context.json:

    {
      "name": "postgres",
      "params": {
        "host": "postgres-host",
        "port": 5432,
        "user": "user",
        "password": "pass",
        "database": "predictionio"
      }
    }
    
  • App ID Isolation Use separate appIds for different environments (dev/staging/prod) in conf/engine.json.

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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity