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

Odataphpprod Laravel Package

adrotec/odataphpprod

Unmaintained PHP OData (v2) producer/server library for exposing read-only data sources. Supports Atom and JSON, $metadata, feeds/entries/properties, paging and query options ($filter, $select, $expand, $orderby, $top, $skip), plus optional media streaming.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require adrotec/odataphpprod:^1.1.0
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        Adrotec\ODataPhpProd\ODataPhpProdServiceProvider::class,
    ],
    
  2. Basic Route Definition Define an OData route in routes/web.php or routes/api.php:

    Route::odata('/odata', function() {
        return new \Adrotec\ODataPhpProd\ODataController();
    });
    
  3. First Use Case: Simple Entity Exposure Create a model (e.g., Product) and expose it via OData:

    use Adrotec\ODataPhpProd\ODataModel;
    
    class Product extends Model implements ODataModel
    {
        public static function getODataProperties()
        {
            return [
                'id' => 'id',
                'name' => 'name',
                'price' => 'price',
            ];
        }
    }
    

    Access via:

    GET /odata/Products
    

Implementation Patterns

Common Workflows

(Unchanged from previous version)

  1. CRUD Operations

    • Read: /odata/Products (GET)
    • Create: /odata/Products (POST with JSON payload)
    • Update: /odata/Products(1) (PATCH/PUT)
    • Delete: /odata/Products(1) (DELETE)
  2. Querying with OData Syntax Filter:

    GET /odata/Products?$filter=price gt 100
    

    Ordering:

    GET /odata/Products?$orderby=name desc
    

    Paging:

    GET /odata/Products?$top=10&$skip=20
    
  3. Relationships Define relationships in getODataProperties():

    public static function getODataProperties()
    {
        return [
            'id' => 'id',
            'category' => [
                'entity' => 'Category',
                'foreignKey' => 'category_id',
            ],
        ];
    }
    

    Access via:

    GET /odata/Products(1)/category
    
  4. Custom Actions Define actions in getODataActions():

    public static function getODataActions()
    {
        return [
            'getDiscountedPrice' => [
                'httpMethod' => 'GET',
                'parameters' => [
                    'discountPercentage' => ['type' => 'Edm.Double'],
                ],
            ],
        ];
    }
    

    Invoke via:

    POST /odata/Products(1)/getDiscountedPrice(discountPercentage=20)
    
  5. Integration with Laravel Eloquent Use Eloquent models directly:

    class ProductController extends ODataController
    {
        protected $model = \App\Models\Product::class;
    }
    

Integration Tips

(Unchanged from previous version)

  1. Authentication/Middleware Apply middleware to OData routes:

    Route::odata('/odata', function() {
        return new \Adrotec\ODataPhpProd\ODataController();
    })->middleware('auth:api');
    
  2. CORS Configuration Ensure CORS headers are set for OData endpoints if used in SPAs:

    Route::middleware('cors:api')->odata('/odata', ...);
    
  3. Validation Use Laravel’s validation for custom actions:

    public function getDiscountedPrice($key, $parameters)
    {
        $validator = Validator::make($parameters, [
            'discountPercentage' => 'required|numeric|min:0|max:100',
        ]);
        // ...
    }
    
  4. Logging Log OData requests for debugging:

    Route::odata('/odata', function() {
        \Log::info('OData request received');
        return new \Adrotec\ODataPhpProd\ODataController();
    });
    

Gotchas and Tips

Pitfalls

  1. Deprecated Package

    • Last release in 2017; may not support Laravel 8/9+ out-of-the-box.
    • Workaround: Use a compatibility layer or fork the package.
  2. No Built-in Caching

    • OData queries are not cached by default. Implement caching manually:
      $cacheKey = 'odata_products_' . md5($request->getQueryString());
      return Cache::remember($cacheKey, now()->addMinutes(10), function() use ($request) {
          return $this->query($request);
      });
      
  3. Limited Laravel Integration

    • Assumes basic Eloquent usage. Custom logic (e.g., soft deletes) may require overrides:
      public function query($request)
      {
          $query = parent::query($request);
          return $query->withTrashed(); // Example for soft deletes
      }
      
  4. No Built-in Error Handling

    • Customize error responses in a controller:
      public function handleError($exception)
      {
          return response()->json([
              'error' => $exception->getMessage(),
          ], 500);
      }
      
  5. Performance with Complex Queries

    • Avoid $expand with deep relationships without limits:
      GET /odata/Products?$expand=category($expand=supplier)
      
    • Tip: Add depth limits or use lazy loading.
  6. Reserved Keyword in Metadata Types

    • Breaking Change: The String class in ODataProducer\Providers\Metadata\Type was renamed to StringType in 1.1.0 due to PHP7+ reserved keywords.
    • Impact: Any custom metadata providers or extensions using String class must be updated to StringType.
    • Fix: Replace:
      use ODataProducer\Providers\Metadata\Type\String;
      
      with:
      use ODataProducer\Providers\Metadata\Type\StringType;
      

Debugging Tips

(Unchanged from previous version)

  1. Enable Query Logging Add to AppServiceProvider:

    public function boot()
    {
        \DB::enableQueryLog();
    }
    

    Log queries in OData actions:

    \Log::debug('Query:', \DB::getQueryLog());
    
  2. Validate OData Syntax Use tools like OData Validator to test queries before implementing.

  3. Check Request Payloads For POST/PATCH, log raw input:

    \Log::debug('Request payload:', $request->getContent());
    

Extension Points

(Unchanged from previous version, except for updated namespace)

  1. Custom Metadata Extend getODataMetadata() for custom EDM definitions:

    public static function getODataMetadata()
    {
        return [
            'namespace' => 'MyNamespace',
            'entities' => [
                'Product' => [
                    'properties' => [
                        'id' => ['type' => 'Edm.Int32'],
                        'name' => ['type' => 'Edm.String'], // Use 'Edm.String' instead of 'String'
                    ],
                ],
            ],
        ];
    }
    
  2. Dynamic Properties Use closures for dynamic properties:

    public static function getODataProperties()
    {
        return [
            'id' => 'id',
            'formattedPrice' => function($model) {
                return '$' . number_format($model->price, 2);
            },
        ];
    }
    
  3. Override Default Behavior Extend the base controller:

    class CustomODataController extends \Adrotec\ODataPhpProd\ODataController
    {
        public function query($request)
        {
            $query = parent::query($request);
            // Add global scope or filters
            return $query->where('active', 1);
        }
    }
    
  4. Add Custom Providers Register additional OData providers in ODataPhpProdServiceProvider:

    $this->app->bind(
        \Adrotec\ODataPhpProd\ODataProvider::class,
        \App\Providers\CustomODataProvider::class
    );
    
    • Note: Ensure any custom metadata types use the updated StringType class.
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.
althinect/enum-permission
andydefer/laravel-actions
aimeos/prisma
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
christhompsontldr/laravel-inky
spatie/mailcoach-vapor