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

Mynosql Laravel Package

dovstone/mynosql

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dovstone/mynosql
    

    Add to config/app.php under providers:

    DovStone\MyNoSQL\MyNoSQLServiceProvider::class,
    

    Publish config (if available) with:

    php artisan vendor:publish --provider="DovStone\MyNoSQL\MyNoSQLServiceProvider"
    
  2. First Use Case: Inject the HostConnection via Laravel's DI container:

    use DovStone\MyNoSQL\HostConnection;
    
    class MyController extends Controller {
        public function __construct(HostConnection $db) {
            $this->db = $db;
        }
    }
    

    Or fetch via facade (if provided):

    $db = \MyNoSQL::connection('mysql:host=localhost;dbname=mynosql', 'root', '');
    
  3. Basic CRUD:

    // Insert
    $doc = $this->db->collection('users')->insert(['name' => 'John', 'email' => 'john@example.com']);
    
    // Find
    $user = $this->db->collection('users')->find($doc->id)->fetch();
    
    // Update
    $this->db->collection('users')->update($doc->id, ['name' => 'John Doe']);
    
    // Delete
    $this->db->collection('users')->delete($doc->id);
    

Implementation Patterns

Laravel Integration

  1. Service Provider Binding: Bind the HostConnection to the container in AppServiceProvider:

    $this->app->singleton('mynosql', function ($app) {
        return new HostConnection(
            config('mynosql.connection'),
            config('mynosql.username'),
            config('mynosql.password')
        );
    });
    
  2. Eloquent-like Usage: Create a base model for collections:

    class UserModel {
        protected $collection = 'users';
        protected $db;
    
        public function __construct(HostConnection $db) {
            $this->db = $db;
        }
    
        public function find($id) {
            return $this->db->collection($this->collection)->find($id)->fetch();
        }
    
        public function all() {
            return $this->db->collection($this->collection)->findAll()->fetch();
        }
    }
    
  3. Query Builder Chaining: Leverage chainable methods for fluent queries:

    $activeUsers = $this->db->collection('users')
        ->findBy(['active' => true])
        ->orderBy(['name' => 'asc'])
        ->limit(10)
        ->fetch();
    
  4. Repository Pattern: Encapsulate logic in repositories:

    class UserRepository {
        public function __construct(HostConnection $db) {
            $this->db = $db;
        }
    
        public function getActiveUsersWithLimit(int $limit) {
            return $this->db->collection('users')
                ->findBy(['active' => true])
                ->limit($limit)
                ->fetch();
        }
    }
    
  5. Transactions: Wrap operations in transactions (if supported):

    DB::transaction(function () use ($db) {
        $db->collection('users')->insert($userData);
        $db->collection('logs')->insert($logData);
    });
    

Gotchas and Tips

Pitfalls

  1. No Native Laravel Eloquent:

    • Avoid assuming Eloquent ORM features (e.g., relationships, events). Use raw queries or build custom logic.
    • Example: No hasMany or belongsTo out of the box.
  2. Schema Limitations:

    • Collections are schema-less, but complex nested arrays may require manual serialization/deserialization.
    • Example: Store JSON strings for nested data:
      $db->collection('users')->insert([
          'name' => 'Alice',
          'address' => json_encode(['city' => 'NY', 'zip' => '10001'])
      ]);
      
  3. Performance Quirks:

    • findAllBy and findBy with large datasets may be slow. Use limit/offset for pagination.
    • Avoid findAll on large collections; use criteria-based queries instead.
  4. Error Handling:

    • No built-in query builder exceptions. Wrap operations in try-catch:
      try {
          $user = $this->db->collection('users')->find($id)->fetch();
      } catch (\Exception $e) {
          Log::error("MyNoSQL Error: " . $e->getMessage());
          abort(500);
      }
      
  5. Connection Management:

    • Reuse HostConnection instances. Creating new instances per request may cause overhead.
    • Example: Store in a singleton or use Laravel's container.

Debugging Tips

  1. Query Logging:

    • Enable MySQL general query log to inspect underlying SQL:
      SET GLOBAL general_log = 'ON';
      SET GLOBAL general_log_file = '/tmp/mynosql.log';
      
    • Parse logs to understand how MyNoSQL translates NoSQL operations to SQL.
  2. Fetch Behavior:

    • fetch() returns raw arrays. Ensure data types match expectations (e.g., JSON-decoded fields).
  3. Criteria Syntax:

    • Criteria arrays use exact matching (e.g., ['status' => 'active']). For partial matches, use LIKE or full-text search manually:
      $this->db->collection('users')
          ->findBy(['name' => ['like', '%ohn%']]) // Hypothetical; may need custom logic
          ->fetch();
      

Extension Points

  1. Custom Query Methods:

    • Extend HostConnection to add domain-specific queries:
      class ExtendedHostConnection extends HostConnection {
          public function findUsersByRole(string $role) {
              return $this->collection('users')
                  ->findBy(['role' => $role])
                  ->fetch();
          }
      }
      
  2. Event Listeners:

    • Hook into Laravel events to trigger actions on MyNoSQL operations:
      Event::listen('eloquent.saved', function ($model) {
          // Sync with MyNoSQL if using hybrid storage
      });
      
  3. Middleware:

    • Add middleware to transform input/output data:
      $db->collection('users')->insert($data)->then(function ($result) {
          // Post-process result
      });
      
  4. Hybrid Storage:

    • Combine with Eloquent for relational data and MyNoSQL for flexible schemas:
      // Eloquent for users, MyNoSQL for user preferences
      $user = User::find(1);
      $prefs = $this->db->collection('user_prefs')->find($user->id)->fetch();
      
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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope